<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html><head>
<link rel="STYLESHEET" href="opencvref.css" charset="ISO-8859-1" type="text/css">
<title>CXCORE Reference Manual</title>
</head><body>

<h1>CXCORE Reference Manual</h1>

<hr><p><ul>
<li><a href="#cxcore_basic_structures">Basic Structures</a>
<li><a href="#cxcore_arrays">Operations on Arrays</a>
<ul>
<li><a href="#cxcore_arrays_alloc_free">Initialization</a>
<li><a href="#cxcore_arrays_get_set">Accessing Elements and sub-Arrays</a>
<li><a href="#cxcore_arrays_copying">Copying and Filling</a>
<li><a href="#cxcore_arrays_permute">Transforms and Permutations</a>
<li><a href="#cxcore_arrays_arithm_logic">Arithmetic, Logic and Comparison</a>
<li><a href="#cxcore_arrays_stat">Statistics</a>
<li><a href="#cxcore_arrays_matrix">Linear Algebra</a>
<li><a href="#cxcore_arrays_math">Math Functions</a>
<li><a href="#cxcore_arrays_rng">Random Number Generation</a>
<li><a href="#cxcore_arrays_dxt">Discrete Transforms</a>
</ul>
<li><a href="#cxcore_ds">Dynamic Structures</a>
<ul>
<li><a href="#cxcore_ds_storages">Memory Storages</a>
<li><a href="#cxcore_ds_sequences">Sequences</a>
<li><a href="#cxcore_ds_sets">Sets</a>
<li><a href="#cxcore_ds_graphs">Graphs</a>
<li><a href="#cxcore_ds_trees">Trees</a>
</ul>
<li><a href="#cxcore_drawing">Drawing Functions</a>
<ul>
<li><a href="#cxcore_drawing_shapes">Curves and Shapes</a>
<li><a href="#cxcore_drawing_text">Text</a>
<li><a href="#cxcore_drawing_seq">Point Sets and Contours</a>
</ul>
<li><a href="#cxcore_persistence">Data Persistence and RTTI</a>
<ul>
<li><a href="#cxcore_persistence_ds">File Storage</a>
<li><a href="#cxcore_persistence_writing">Writing Data</a>
<li><a href="#cxcore_persistence_reading">Reading Data</a>
<li><a href="#cxcore_persistence_rtti">RTTI and Generic Functions</a>
</ul>
<li><a href="#cxcore_misc">Miscellaneous Functions</a>
<li><a href="#cxcore_system">Error Handling and System Functions</a>
<ul>
<li><a href="#cxcore_system_error">Error Handling</a>
<li><a href="#cxcore_system_sys">System Functions</a>
</ul>
<li><a href="#cxcore_func_index">Alphabetical List of Functions</a>
<li><a href="#cxcore_sample_index">List of Examples</a>
</ul></p>


<!-- *****************************************************************************************
     *****************************************************************************************
     ***************************************************************************************** -->

<hr><h1><a name="cxcore_basic_structures">Basic Structures</a></h1>

<hr><h3><a name="decl_CvPoint">CvPoint</a></h3>
<p class="Blurb">2D point with integer coordinates</p>
<pre>
    typedef struct CvPoint
    {
        int x; /* x-coordinate, usually zero-based */
        int y; /* y-coordinate, usually zero-based */
    }
    CvPoint;

    /* the constructor function */
    inline CvPoint cvPoint( int x, int y );

    /* conversion from CvPoint2D32f */
    inline CvPoint cvPointFrom32f( CvPoint2D32f point );
</pre>

<hr><h3><a name="decl_CvPoint2D32f">CvPoint2D32f</a></h3>
<p class="Blurb">2D point with floating-point coordinates</p>
<pre>
    typedef struct CvPoint2D32f
    {
        float x; /* x-coordinate, usually zero-based */
        float y; /* y-coordinate, usually zero-based */
    }
    CvPoint2D32f;

    /* the constructor function */
    inline CvPoint2D32f cvPoint2D32f( double x, double y );

    /* conversion from CvPoint */
    inline CvPoint2D32f cvPointTo32f( CvPoint point );
</pre>


<hr><h3><a name="decl_CvPoint3D32f">CvPoint3D32f</a></h3>
<p class="Blurb">3D point with floating-point coordinates</p>
<pre>
    typedef struct CvPoint3D32f
    {
        float x; /* x-coordinate, usually zero-based */
        float y; /* y-coordinate, usually zero-based */
        float z; /* z-coordinate, usually zero-based */
    }
    CvPoint3D32f;

    /* the constructor function */
    inline CvPoint3D32f cvPoint3D32f( double x, double y, double z );
</pre>


<hr><h3><a name="decl_CvPoint2D64f">CvPoint2D64f</a></h3>
<p class="Blurb">2D point with double precision floating-point coordinates</p>
<pre>
    typedef struct CvPoint2D64f
    {
        double x; /* x-coordinate, usually zero-based */
        double y; /* y-coordinate, usually zero-based */
    }
    CvPoint2D64f;

    /* the constructor function */
    inline CvPoint2D64f cvPoint2D64f( double x, double y );

    /* conversion from CvPoint */
    inline CvPoint2D64f cvPointTo64f( CvPoint point );
</pre>


<hr><h3><a name="decl_CvPoint3D64f">CvPoint3D64f</a></h3>
<p class="Blurb">3D point with double precision floating-point coordinates</p>
<pre>
    typedef struct CvPoint3D64f
    {
        double x; /* x-coordinate, usually zero-based */
        double y; /* y-coordinate, usually zero-based */
        double z; /* z-coordinate, usually zero-based */
    }
    CvPoint3D64f;

    /* the constructor function */
    inline CvPoint3D64f cvPoint3D64f( double x, double y, double z );
</pre>


<hr><h3><a name="decl_CvSize">CvSize</a></h3>
<p class="Blurb">pixel-accurate size of a rectangle</p>
<pre>
    typedef struct CvSize
    {
        int width; /* width of the rectangle */
        int height; /* height of the rectangle */
    }
    CvSize;

    /* the constructor function */
    inline CvSize cvSize( int width, int height );
</pre>


<hr><h3><a name="decl_CvSize2D32f">CvSize2D32f</a></h3>
<p class="Blurb">sub-pixel accurate size of a rectangle</p>
<pre>
    typedef struct CvSize2D32f
    {
        float width; /* width of the box */
        float height; /* height of the box */
    }
    CvSize2D32f;

    /* the constructor function */
    inline CvSize2D32f cvSize2D32f( double width, double height );
</pre>


<hr><h3><a name="decl_CvRect">CvRect</a></h3>
<p class="Blurb">offset and size of a rectangle</p>
<pre>
    typedef struct CvRect
    {
        int x; /* x-coordinate of the left-most rectangle corner[s] */
        int y; /* y-coordinate of the top-most or bottom-most
                  rectangle corner[s] */
        int width; /* width of the rectangle */
        int height; /* height of the rectangle */
    }
    CvRect;

    /* the constructor function */
    inline CvRect cvRect( int x, int y, int width, int height );
</pre>


<hr><h3><a name="decl_CvScalar">CvScalar</a></h3>
<p class="Blurb">A container for 1-,2-,3- or 4-tuples of numbers</p>
<pre>
    typedef struct CvScalar
    {
        double val[4];
    }
    CvScalar;

    /* the constructor function: initializes val[0] with val0, val[1] with val1 etc. */
    inline CvScalar cvScalar( double val0, double val1=0,
                              double val2=0, double val3=0 );
    /* the constructor function: initializes val[0]...val[3] with val0123 */
    inline CvScalar cvScalarAll( double val0123 );

    /* the constructor function: initializes val[0] with val0, val[1]...val[3] with zeros */
    inline CvScalar cvRealScalar( double val0 );
</pre>


<hr><h3><a name="decl_CvTermCriteria">CvTermCriteria</a></h3>
<p class="Blurb">Termination criteria for iterative algorithms</p>
<pre>
#define CV_TERMCRIT_ITER    1
#define CV_TERMCRIT_NUMBER  CV_TERMCRIT_ITER
#define CV_TERMCRIT_EPS     2

typedef struct CvTermCriteria
{
    int    type;  /* a combination of CV_TERMCRIT_ITER and CV_TERMCRIT_EPS */
    int    max_iter; /* maximum number of iterations */
    double epsilon; /* accuracy to achieve */
}
CvTermCriteria;

/* the constructor function */
inline  CvTermCriteria  cvTermCriteria( int type, int max_iter, double epsilon );

/* check termination criteria and transform it so that type=CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
   and both max_iter and epsilon are valid */
CvTermCriteria cvCheckTermCriteria( CvTermCriteria criteria,
                                    double default_eps,
                                    int default_max_iters );
</pre>


<!-- *****************************************************************************************
     *****************************************************************************************
     ***************************************************************************************** -->

<!-- <hr><h2><a name="ch1_array_structs">Array structures</a></h2> -->

<hr><h3><a name="decl_CvMat">CvMat</a></h3>
<p class="Blurb">Multi-channel matrix</p>
<pre>
    typedef struct CvMat
    {
        int type; /* CvMat signature (CV_MAT_MAGIC_VAL), element type and flags */
        int step; /* full row length in bytes */

        int* refcount; /* underlying data reference counter */

        union
        {
            uchar* ptr;
            short* s;
            int* i;
            float* fl;
            double* db;
        } data; /* data pointers */

    #ifdef __cplusplus
        union
        {
            int rows;
            int height;
        };

        union
        {
            int cols;
            int width;
        };
    #else
        int rows; /* number of rows */
        int cols; /* number of columns */
    #endif

    } CvMat;
</pre>


<hr><h3><a name="decl_CvMatND">CvMatND</a></h3>
<p class="Blurb">Multi-dimensional dense multi-channel array</p>
<pre>
    typedef struct CvMatND
    {
        int type; /* CvMatND signature (CV_MATND_MAGIC_VAL), element type and flags */
        int dims; /* number of array dimensions */

        int* refcount; /* underlying data reference counter */

        union
        {
            uchar* ptr;
            short* s;
            int* i;
            float* fl;
            double* db;
        } data; /* data pointers */

        /* pairs (number of elements, distance between elements in bytes) for
           every dimension */
        struct
        {
            int size;
            int step;
        }
        dim[CV_MAX_DIM];

    } CvMatND;
</pre>


<hr><h3><a name="decl_CvSparseMat">CvSparseMat</a></h3>
<p class="Blurb">Multi-dimensional sparse multi-channel array</p>
<pre>
    typedef struct CvSparseMat
    {
        int type; /* CvSparseMat signature (CV_SPARSE_MAT_MAGIC_VAL), element type and flags */
        int dims; /* number of dimensions */
        int* refcount; /* reference counter - not used */
        struct CvSet* heap; /* a pool of hashtable nodes */
        void** hashtable; /* hashtable: each entry has a list of nodes
                             having the same "hashvalue modulo hashsize" */
        int hashsize; /* size of hashtable */
        int total; /* total number of sparse array nodes */
        int valoffset; /* value offset in bytes for the array nodes */
        int idxoffset; /* index offset in bytes for the array nodes */
        int size[CV_MAX_DIM]; /* arr of dimension sizes */

    } CvSparseMat;
</pre>


<hr><h3><a name="decl_IplImage">IplImage</a></h3>
<p class="Blurb">IPL image header</p>
<pre>
    typedef struct _IplImage
    {
        int  nSize;         /* sizeof(IplImage) */
        int  ID;            /* version (=0)*/
        int  nChannels;     /* Most of OpenCV functions support 1,2,3 or 4 channels */
        int  alphaChannel;  /* ignored by OpenCV */
        int  depth;         /* pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16U,
                               IPL_DEPTH_16S, IPL_DEPTH_32S, IPL_DEPTH_32F and IPL_DEPTH_64F are supported */
        char colorModel[4]; /* ignored by OpenCV */
        char channelSeq[4]; /* ditto */
        int  dataOrder;     /* 0 - interleaved color channels, 1 - separate color channels.
                               cvCreateImage can only create interleaved images */
        int  origin;        /* 0 - top-left origin,
                               1 - bottom-left origin (Windows bitmaps style) */
        int  align;         /* Alignment of image rows (4 or 8).
                               OpenCV ignores it and uses widthStep instead */
        int  width;         /* image width in pixels */
        int  height;        /* image height in pixels */
        struct _IplROI *roi;/* image ROI. when it is not NULL, this specifies image region to process */
        struct _IplImage *maskROI; /* must be NULL in OpenCV */
        void  *imageId;     /* ditto */
        struct _IplTileInfo *tileInfo; /* ditto */
        int  imageSize;     /* image data size in bytes
                               (=image->height*image->widthStep
                               in case of interleaved data)*/
        char *imageData;  /* pointer to aligned image data */
        int  widthStep;   /* size of aligned image row in bytes */
        int  BorderMode[4]; /* border completion mode, ignored by OpenCV */
        int  BorderConst[4]; /* ditto */
        char *imageDataOrigin; /* pointer to a very origin of image data
                                  (not necessarily aligned) -
                                  it is needed for correct image deallocation */
    }
    IplImage;
</pre>
<p>
The structure <code>IplImage</code> came from <em>Intel Image Processing Library</em> where
the format is native. OpenCV supports only a subset of possible <code>IplImage</code> formats:
<ul>
<li><code>alphaChannel</code> is ignored by OpenCV.
<li><code>colorModel</code> and <code>channelSeq</code> are ignored by OpenCV. The single OpenCV function
<a href="#decl_cvCvtColor">cvCvtColor</a> working with color spaces takes the source and destination color spaces
as a parameter.
<li><code>dataOrder</code> must be IPL_DATA_ORDER_PIXEL (the color channels are interleaved), however
selected channels of planar images can be processed as well if COI is set.
<li><code>align</code> is ignored by OpenCV, while <code>widthStep</code> is used to access to subsequent image rows.
<li><code>maskROI</code> is not supported. The function that can work with mask take it as a
separate parameter. Also the mask in OpenCV is 8-bit, whereas in IPL it is 1-bit.
<li><code>tileInfo</code> is not supported.
<li><code>BorderMode</code> and <code>BorderConst</code> are not supported. Every OpenCV function
working with a pixel neigborhood uses a single hard-coded border mode (most often, replication).
</ul>
Besides the above restrictions, OpenCV handles ROI differently. It requires that the sizes or ROI sizes of
all source and destination images match exactly (according to the operation, e.g. for <a href="#decl_cvPyrDown">cvPyrDown</a>
destination width(height) must be equal to source width(height) divided by 2 &plusmn;1),
whereas IPL processes the intersection area - that is, the sizes or ROI sizes of all images may
vary independently.
</p>


<hr><h3><a name="decl_CvArr">CvArr</a></h3>
<p class="Blurb">Arbitrary array</p>
<pre>
    typedef void CvArr;
</pre>
<p>
The metatype <code>CvArr*</code> is used <em>only</em> as a function parameter to
specify that the function accepts arrays of more than a
single type, for example IplImage*, CvMat* or even CvSeq*. The particular array
type is determined at runtime by analyzing the first 4 bytes of the header.
</p>

<!-- *****************************************************************************************
     *****************************************************************************************
     ***************************************************************************************** -->

<hr><h1><a name="cxcore_arrays">Operations on Arrays</a></h1>
<hr><h2><a name="cxcore_arrays_alloc_free">Initialization</a></h2>

<hr><h3><a name="decl_cvCreateImage">CreateImage</a></h3>
<p class="Blurb">Creates header and allocates data</p>
<pre>
IplImage* cvCreateImage( CvSize size, int depth, int channels );
</pre><p><dl>
<dt>size<dd>Image width and height.
<dt>depth<dd>Bit depth of image elements. Can be one of:<br>
             IPL_DEPTH_8U - unsigned 8-bit integers<br>
             IPL_DEPTH_8S - signed 8-bit integers<br>
             IPL_DEPTH_16U - unsigned 16-bit integers<br>
             IPL_DEPTH_16S - signed 16-bit integers<br>
             IPL_DEPTH_32S - signed 32-bit integers<br>
             IPL_DEPTH_32F - single precision floating-point numbers<br>
             IPL_DEPTH_64F - double precision floating-point numbers<br>
<dt>channels<dd>Number of channels per element(pixel). Can be 1, 2, 3 or 4.
             The channels are interleaved, for example the
             usual data layout of a color image is:<br>
             b0 g0 r0 b1 g1 r1 ...<br>
             Although in general IPL image format can store
             non-interleaved images as well and some of OpenCV
             can process it, this function can create interleaved images
             only.
</dl><p>
The function <code>cvCreateImage</code> creates the header and allocates data. This call is a
shortened form of
<pre>
    header = cvCreateImageHeader(size,depth,channels);
    cvCreateData(header);
</pre>
</p>


<hr><h3><a name="decl_cvCreateImageHeader">CreateImageHeader</a></h3>
<p class="Blurb">Allocates, initializes, and returns structure IplImage</p>
<pre>
IplImage* cvCreateImageHeader( CvSize size, int depth, int channels );
</pre><p><dl>
<dt>size<dd>Image width and height.
<dt>depth<dd>Image depth (see CreateImage).
<dt>channels<dd>Number of channels (see CreateImage).
</dl><p>
The function <code>cvCreateImageHeader</code> allocates, initializes, and returns the structure
<code>IplImage</code>. This call is an analogue of
<pre>
  iplCreateImageHeader( channels, 0, depth,
                        channels == 1 ? "GRAY" : "RGB",
                        channels == 1 ? "GRAY" : channels == 3 ? "BGR" :
                        channels == 4 ? "BGRA" : "",
                        IPL_DATA_ORDER_PIXEL, IPL_ORIGIN_TL, 4,
                        size.width, size.height,
                        0,0,0,0);
</pre>
though it does not use IPL functions by default
(see also <code>CV_TURN_ON_IPL_COMPATIBILITY</code> macro)
</p>


<hr><h3><a name="decl_cvReleaseImageHeader">ReleaseImageHeader</a></h3>
<p class="Blurb">Releases header</p>
<pre>
void cvReleaseImageHeader( IplImage** image );
</pre><p><dl>
<dt>image<dd>Double pointer to the deallocated header.
</dl><p>
The function <code>cvReleaseImageHeader</code> releases the header.
This call is an analogue of
<pre>
    if( image )
    {
        iplDeallocate( *image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI );
        *image = 0;
    }
</pre>
though it does not use IPL functions by default
(see also <code>CV_TURN_ON_IPL_COMPATIBILITY</code>)
</p>


<hr><h3><a name="decl_cvReleaseImage">ReleaseImage</a></h3>
<p class="Blurb">Releases header and image data</p>
<pre>
void cvReleaseImage( IplImage** image );
</pre><p><dl>
<dt>image<dd>Double pointer to the header of the deallocated image.
</dl></p><p>
The function <code>cvReleaseImage</code> releases the header and the image data. This call is a
shortened form of
<pre>
    if( *image )
    {
        cvReleaseData( *image );
        cvReleaseImageHeader( image );
    }
</pre>
</p>


<hr><h3><a name="decl_cvInitImageHeader">InitImageHeader</a></h3>
<p class="Blurb">Initializes allocated by user image header</p>
<pre>
IplImage* cvInitImageHeader( IplImage* image, CvSize size, int depth,
                             int channels, int origin=0, int align=4 );
</pre><p><dl>
<dt>image<dd>Image header to initialize.
<dt>size<dd>Image width and height.
<dt>depth<dd>Image depth (see CreateImage).
<dt>channels<dd>Number of channels (see CreateImage).
<dt>origin<dd><code>IPL_ORIGIN_TL</code> or <code>IPL_ORIGIN_BL</code>.
<dt>align<dd>Alignment for image rows, typically 4 or 8 bytes.
</dl></p><p>
The function <code>cvInitImageHeader</code> initializes the image header structure,
pointer to which is passed by the user, and returns the pointer.
</p>


<hr><h3><a name="decl_cvCloneImage">CloneImage</a></h3>
<p class="Blurb">Makes a full copy of image</p>
<pre>
IplImage* cvCloneImage( const IplImage* image );
</pre><p><dl>
<dt>image<dd>Original image.
</dl></p><p>
The function <code>cvCloneImage</code> makes a full copy of the image including
header, ROI and data
</p>


<hr><h3><a name="decl_cvSetImageCOI">SetImageCOI</a></h3>
<p class="Blurb">Sets channel of interest to given value</p>
<pre>
void cvSetImageCOI( IplImage* image, int coi );
</pre><p><dl>
<dt>image<dd>Image header.
<dt>coi<dd>Channel of interest.
</dl><p>
The function <code>cvSetImageCOI</code> sets the channel of interest
to a given value. Value 0 means that all channels are selected,
1 means that the first channel is selected etc.
If ROI is <code>NULL</code> and <code>coi != 0</code>, ROI is allocated.
Note that most of OpenCV functions do not support COI, so
to process separate image/matrix channel one may copy (via <a href="#decl_cvCopy">cvCopy</a> or
<a href="#decl_cvSplit">cvSplit</a>) the channel to separate image/matrix,
process it and copy the result back (via <a href="#decl_cvCopy">cvCopy</a> or <a href="#decl_cvCvtPlaneToPix">cvCvtPlaneToPix</a>)
if need.</p>


<hr><h3><a name="decl_cvGetImageCOI">GetImageCOI</a></h3>
<p class="Blurb">Returns index of channel of interest</p>
<pre>
int cvGetImageCOI( const IplImage* image );
</pre><p><dl>
<dt>image<dd>Image header.
</dl><p>
The function <code>cvGetImageCOI</code> returns channel of interest of
the image (it returns 0 if all the channels are selected).</p>


<hr><h3><a name="decl_cvSetImageROI">SetImageROI</a></h3>
<p class="Blurb">Sets image ROI to given rectangle</p>
<pre>
void cvSetImageROI( IplImage* image, CvRect rect );
</pre><p><dl>
<dt>image<dd>Image header.
<dt>rect<dd>ROI rectangle.
</dl><p>
The function <code>cvSetImageROI</code> sets the image ROI to a given rectangle. If ROI is <code>NULL</code>
and the value of the parameter <code>rect</code> is not equal to the whole image, ROI is
allocated. Unlike COI, most of OpenCV functions do support ROI and treat
it in a way as it would be a separate image (for example, all the pixel
coordinates are counted from top-left or bottom-left
(depending on the image origin) corner of ROI)</p>


<hr><h3><a name="decl_cvResetImageROI">ResetImageROI</a></h3>
<p class="Blurb">Releases image ROI</p>
<pre>
void cvResetImageROI( IplImage* image );
</pre><p><dl>
<dt>image<dd>Image header.
</dl><p>
The function <code>cvResetImageROI</code> releases image ROI. After that the whole image
is considered selected. The similar result can be achieved by</p>
<pre>
cvSetImageROI( image, cvRect( 0, 0, image->width, image->height ));
cvSetImageCOI( image, 0 );
</pre>
<p>
But the latter variant does not deallocate <code>image->roi</code>.
</p>


<hr><h3><a name="decl_cvGetImageROI">GetImageROI</a></h3>
<p class="Blurb">Returns image ROI coordinates</p>
<pre>
CvRect cvGetImageROI( const IplImage* image );
</pre><p><dl>
<dt>image<dd>Image header.
</dl><p>
The function <code>cvGetImageROI</code> returns image ROI coordinates.
The rectangle <a href="#decl_cvRect">cvRect</a>(0,0,image->width,image->height) is returned if
there is no ROI</p>


<hr><h3><a name="decl_cvCreateMat">CreateMat</a></h3>
<p class="Blurb">Creates new matrix</p>
<pre>
CvMat* cvCreateMat( int rows, int cols, int type );
</pre><p><dl>
<dt>rows<dd>Number of rows in the matrix.
<dt>cols<dd>Number of columns in the matrix.
<dt>type<dd>Type of the matrix elements.
            Usually it is specified in form
            <code>CV_&lt;bit_depth&gt;(S|U|F)C&lt;number_of_channels&gt;</code>, for example:<br>
            <code>CV_8UC1</code> means an 8-bit unsigned single-channel matrix,
            <code>CV_32SC2</code> means a 32-bit signed matrix with two channels.
</dl><p>
The function <code>cvCreateMat</code> allocates header for the new matrix and underlying data,
and returns a pointer to the created matrix. It is a short form for:</p>
<pre>
    CvMat* mat = cvCreateMatHeader( rows, cols, type );
    cvCreateData( mat );
</pre><p>
Matrices are stored row by row. All the rows are aligned by 4 bytes.
</p>


<hr><h3><a name="decl_cvCreateMatHeader">CreateMatHeader</a></h3>
<p class="Blurb">Creates new matrix header</p>
<pre>
CvMat* cvCreateMatHeader( int rows, int cols, int type );
</pre><p><dl>
<dt>rows<dd>Number of rows in the matrix.
<dt>cols<dd>Number of columns in the matrix.
<dt>type<dd>Type of the matrix elements (see <a href="#decl_cvCreateMat">cvCreateMat</a>).
</dl><p>
The function <code>cvCreateMatHeader</code> allocates new matrix header and returns pointer to
it. The matrix data can further be allocated using <a href="#decl_cvCreateData">cvCreateData</a> or set
explicitly to user-allocated data via <a href="#decl_cvSetData">cvSetData</a>.
</p>


<hr><h3><a name="decl_cvReleaseMat">ReleaseMat</a></h3>
<p class="Blurb">Deallocates matrix</p>
<pre>
void cvReleaseMat( CvMat** mat );
</pre><p><dl>
<dt>mat<dd>Double pointer to the matrix.
</dl><p>
The function <code>cvReleaseMat</code> decrements the matrix data reference counter and
releases matrix header:</p>
<pre>
    if( *mat )
        cvDecRefData( *mat );
    cvFree( (void**)mat );
</pre>
</p>


<hr><h3><a name="decl_cvInitMatHeader">InitMatHeader</a></h3>
<p class="Blurb">Initializes matrix header</p>
<pre>
CvMat* cvInitMatHeader( CvMat* mat, int rows, int cols, int type,
                        void* data=NULL, int step=CV_AUTOSTEP );
</pre><p><dl>
<dt>mat<dd>Pointer to the matrix header to be initialized.
<dt>rows<dd>Number of rows in the matrix.
<dt>cols<dd>Number of columns in the matrix.
<dt>type<dd>Type of the matrix elements.
<dt>data<dd>Optional data pointer assigned to the matrix header.
<dt>step<dd>Full row width in bytes of the data assigned. By default, the minimal
possible step is used, i.e., no gaps is assumed between subsequent rows of the
matrix.
</dl><p>
The function <code>cvInitMatHeader</code> initializes already allocated <a href="#decl_CvMat">CvMat</a> structure. It can
be used to process raw data with OpenCV matrix functions.
<p>
For example, the following code computes matrix product of two matrices, stored
as ordinary arrays.
</p>
</p><p>
<font color=blue size=4>Calculating Product of Two Matrices</font></p>
<pre>
   double a[] = { 1, 2, 3, 4
                  5, 6, 7, 8,
                  9, 10, 11, 12 };

   double b[] = { 1, 5, 9,
                  2, 6, 10,
                  3, 7, 11,
                  4, 8, 12 };

   double c[9];
   CvMat Ma, Mb, Mc ;

   cvInitMatHeader( &amp;Ma, 3, 4, CV_64FC1, a );
   cvInitMatHeader( &amp;Mb, 4, 3, CV_64FC1, b );
   cvInitMatHeader( &amp;Mc, 3, 3, CV_64FC1, c );

   cvMatMulAdd( &amp;Ma, &amp;Mb, 0, &amp;Mc );
   // c array now contains product of a(3x4) and b(4x3) matrices
</pre></p>


<hr><h3><a name="decl_cvMat">Mat</a></h3>
<p class="Blurb">Initializes matrix header (light-weight variant)</p>
<pre>
CvMat cvMat( int rows, int cols, int type, void* data=NULL );
</pre><p><dl>
<dt>rows<dd>Number of rows in the matrix.
<dt>cols<dd>Number of columns in the matrix.
<dt>type<dd>Type of the matrix elements (see CreateMat).
<dt>data<dd>Optional data pointer assigned to the matrix header.
</dl><p>
The function <code>cvMat</code> is a fast inline substitution for <a href="#decl_cvInitMatHeader">cvInitMatHeader</a>.
Namely, it is equivalent to:
<pre>
     CvMat mat;
     cvInitMatHeader( &amp;mat, rows, cols, type, data, CV_AUTOSTEP );
</pre>
</p>


<hr><h3><a name="decl_cvCloneMat">CloneMat</a></h3>
<p class="Blurb">Creates matrix copy</p>
<pre>
CvMat* cvCloneMat( const CvMat* mat );
</pre><p><dl>
<dt>mat<dd>Input matrix.
</dl><p>
The function <code>cvCloneMat</code> creates a copy of input matrix and returns the pointer to
it.
</p>


<hr><h3><a name="decl_cvCreateMatND">CreateMatND</a></h3>
<p class="Blurb">Creates multi-dimensional dense array</p>
<pre>
CvMatND* cvCreateMatND( int dims, const int* sizes, int type );
</pre><p><dl>
<dt>dims<dd>Number of array dimensions. It must not exceed CV_MAX_DIM (=32 by default,
            though it may be changed at build time)
<dt>sizes<dd>Array of dimension sizes.
<dt>type<dd>Type of array elements. The same as for <a href="#decl_CvMat">CvMat</a>
</dl><p>
The function <code>cvCreateMatND</code> allocates header for multi-dimensional dense array
and the underlying data, and returns pointer to the created array. It is a short form for:</p>
<pre>
    CvMatND* mat = cvCreateMatNDHeader( dims, sizes, type );
    cvCreateData( mat );
</pre><p>
Array data is stored row by row. All the rows are aligned by 4 bytes.
</p>


<hr><h3><a name="decl_cvCreateMatNDHeader">CreateMatNDHeader</a></h3>
<p class="Blurb">Creates new matrix header</p>
<pre>
CvMatND* cvCreateMatNDHeader( int dims, const int* sizes, int type );
</pre><p><dl>
<dt>dims<dd>Number of array dimensions.
<dt>sizes<dd>Array of dimension sizes.
<dt>type<dd>Type of array elements. The same as for CvMat
</dl><p>
The function <code>cvCreateMatND</code> allocates header for multi-dimensional dense array.
The array data can further be allocated using <a href="#decl_cvCreateData">cvCreateData</a> or set
explicitly to user-allocated data via <a href="#decl_cvSetData">cvSetData</a>.
</p>


<hr><h3><a name="decl_cvReleaseMatND">ReleaseMatND</a></h3>
<p class="Blurb">Deallocates multi-dimensional array</p>
<pre>
void cvReleaseMatND( CvMatND** mat );
</pre><p><dl>
<dt>mat<dd>Double pointer to the array.
</dl><p>
The function <code>cvReleaseMatND</code> decrements the array data reference counter and
releases the array header:</p>
<pre>
    if( *mat )
        cvDecRefData( *mat );
    cvFree( (void**)mat );
</pre>
</p>


<hr><h3><a name="decl_cvInitMatNDHeader">InitMatNDHeader</a></h3>
<p class="Blurb">Initializes multi-dimensional array header</p>
<pre>
CvMatND* cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes, int type, void* data=NULL );
</pre><p><dl>
<dt>mat<dd>Pointer to the array header to be initialized.
<dt>dims<dd>Number of array dimensions.
<dt>sizes<dd>Array of dimension sizes.
<dt>type<dd>Type of array elements. The same as for CvMat
<dt>data<dd>Optional data pointer assigned to the matrix header.
</dl><p>
The function <code>cvInitMatNDHeader</code> initializes <a href="#decl_CvMatND">CvMatND</a> structure allocated by
the user.
</p>


<hr><h3><a name="decl_cvCloneMatND">CloneMatND</a></h3>
<p class="Blurb">Creates full copy of multi-dimensional array</p>
<pre>
CvMatND* cvCloneMatND( const CvMatND* mat );
</pre><p><dl>
<dt>mat<dd>Input array.
</dl><p>
The function <code>cvCloneMatND</code> creates a copy of input array and returns pointer to
it.
</p>


<hr><h3><a name="decl_cvDecRefData">DecRefData</a></h3>
<p class="Blurb">Decrements array data reference counter</p>
<pre>
void cvDecRefData( CvArr* arr );
</pre><p><dl>
<dt>arr<dd>array header.
</dl><p>
The function <code>cvDecRefData</code> decrements <a href="#decl_CvMat">CvMat</a> or <a href="#decl_CvMatND">CvMatND</a> data reference counter if the
reference counter pointer is not NULL and deallocates the data if the counter reaches zero.
In the current implementation the reference counter is not NULL only if the data was allocated using
<a href="#decl_cvCreateData">cvCreateData</a> function, in other cases such as:<br>
external data was assigned to the header using <a href="#decl_cvSetData">cvSetData</a><br>
the matrix header presents a part of a larger matrix or image<br>
the matrix header was converted from image or n-dimensional matrix header<br>
<br>
the reference counter is set to NULL and thus it is not decremented.
Whenever the data is deallocated or not,
the data pointer and reference counter pointers are cleared by the function.
</p>


<hr><h3><a name="decl_cvIncRefData">IncRefData</a></h3>
<p class="Blurb">Increments array data reference counter</p>
<pre>
int cvIncRefData( CvArr* arr );
</pre><p><dl>
<dt>arr<dd>array header.
</dl><p>
The function <code>cvIncRefData</code> increments <a href="#decl_CvMat">CvMat</a> or <a href="#decl_CvMatND">CvMatND</a> data reference counter and
returns the new counter value if the reference counter pointer is not NULL, otherwise it returns zero.
</p>


<hr><h3><a name="decl_cvCreateData">CreateData</a></h3>
<p class="Blurb">Allocates array data</p>
<pre>
void cvCreateData( CvArr* arr );
</pre><p><dl>
<dt>arr<dd>Array header.
</dl></p><p>
The function <code>cvCreateData</code> allocates image, matrix or multi-dimensional array data.
Note that in case of matrix types OpenCV allocation functions are used and
in case of IplImage they are used too unless <code>CV_TURN_ON_IPL_COMPATIBILITY</code> was called.
In the latter case IPL functions are used to allocate the data
</p>


<hr><h3><a name="decl_cvReleaseData">ReleaseData</a></h3>
<p class="Blurb">Releases array data</p>
<pre>
void cvReleaseData( CvArr* arr );
</pre><p><dl>
<dt>arr<dd>Array header
</dl><p>
The function <code>cvReleaseData</code> releases the array data.
In case of <a href="#decl_CvMat">CvMat</a> or <a href="#decl_CvMatND">CvMatND</a> it simply calls cvDecRefData(), that is
the function can not deallocate external data. See also the note to <a href="#decl_cvCreateData">cvCreateData</a>.
</p>


<hr><h3><a name="decl_cvSetData">SetData</a></h3>
<p class="Blurb">Assigns user data to the array header</p>
<pre>
void cvSetData( CvArr* arr, void* data, int step );
</pre><p><dl>
<dt>arr<dd>Array header.
<dt>data<dd>User data.
<dt>step<dd>Full row length in bytes.
</dl><p>
The function <code>cvSetData</code> assigns user data to the array header.
Header should be initialized before using cvCreate*Header,
cvInit*Header or <a href="#decl_cvMat">cvMat</a> (in case of matrix) function.
</p>


<hr><h3><a name="decl_cvGetRawData">GetRawData</a></h3>
<p class="Blurb">Retrieves low-level information about the array</p>
<pre>
void cvGetRawData( const CvArr* arr, uchar** data,
                   int* step=NULL, CvSize* roi_size=NULL );
</pre><p><dl>
<dt>arr<dd>Array header.
<dt>data<dd>Output pointer to the whole image origin or ROI origin if
ROI is set.
<dt>step<dd>Output full row length in bytes.
<dt>roi_size<dd>Output ROI size.
</dl><p>
The function <code>cvGetRawData</code> fills output variables with low-level
information about the array data.
All output parameters are optional, so some of the pointers
may be set to <code>NULL</code>.
If the array is <code>IplImage</code> with ROI set,
parameters of ROI are returned.
</p>
<p>The following example shows how to get access to array elements using
this function.</p>
<p>
<font color=blue size=4>Using GetRawData to calculate absolute value of elements of
a single-channel floating-point array.</font>
<pre>
    float* data;
    int step;

    CvSize size;
    int x, y;

    cvGetRawData( array, (uchar**)&amp;data, &amp;step, &amp;size );
    step /= sizeof(data[0]);

    for( y = 0; y &lt; size.height; y++, data += step )
        for( x = 0; x &lt; size.width; x++ )
            data[x] = (float)fabs(data[x]);
</pre></p>


<hr><h3><a name="decl_cvGetMat">GetMat</a></h3>
<p class="Blurb">Returns matrix header for arbitrary array</p>
<pre>
CvMat* cvGetMat( const CvArr* arr, CvMat* header, int* coi=NULL, int allowND=0 );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>header<dd>Pointer to <a href="#decl_CvMat">CvMat</a> structure used as a temporary buffer.
<dt>coi<dd>Optional output parameter for storing COI.
<dt>allowND<dd>If non-zero, the function accepts multi-dimensional dense
              arrays (CvMatND*) and returns 2D (if CvMatND has two dimensions)
              or 1D matrix (when CvMatND has 1 dimension or more than 2 dimensions).
              The array must be continuous.
</dl><p>
The function <code>cvGetMat</code> returns matrix header for the input array that can be
matrix - <a href="#decl_CvMat">CvMat</a>, image - <code>IplImage</code> or multi-dimensional dense array - <a href="#decl_CvMatND*">CvMatND*</a>
(latter case is allowed only if <code>allowND != 0</code>) .
In the case of matrix the function simply returns the input pointer.
In the case of <code>IplImage*</code> or <a href="#decl_CvMatND*">CvMatND*</a> it initializes <code>header</code> structure
with parameters of the current image ROI and returns pointer to this temporary
structure. Because COI is not supported by <a href="#decl_CvMat">CvMat</a>, it is returned separately.
<p>
The function provides an easy way to handle both types of array - <code>IplImage</code> and
<a href="#decl_CvMat">CvMat</a> -, using the same code. Reverse transform from <a href="#decl_CvMat">CvMat</a> to <code>IplImage</code> can be
done using <a href="#decl_cvGetImage">cvGetImage</a> function.
</p><p>
Input array must have underlying data allocated or attached, otherwise the
function fails.
</p>
If the input array is <code>IplImage</code> with planar data layout and COI set, the function
returns pointer to the selected plane and COI = 0. It enables per-plane
processing of multi-channel images with planar data layout using OpenCV
functions.</p>


<hr><h3><a name="decl_cvGetImage">GetImage</a></h3>
<p class="Blurb">Returns image header for arbitrary array</p>
<pre>
IplImage* cvGetImage( const CvArr* arr, IplImage* image_header );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>image_header<dd>Pointer to <code>IplImage</code> structure used as a temporary buffer.
</dl><p>
The function <code>cvGetImage</code> returns image header for the input array that can be
matrix - <a href="#decl_CvMat*">CvMat*</a>, or image - <code>IplImage*</code>. In the case of image the function simply
returns the input pointer. In the case of <a href="#decl_CvMat*">CvMat*</a> it initializes <code>image_header</code> structure
with parameters of the input matrix. Note that if we transform <code>IplImage</code> to <a href="#decl_CvMat">CvMat</a> and then transform
CvMat back to IplImage, we can get different headers if the ROI is set, and thus some IPL functions
that calculate image stride from its width and align may fail on the resultant image.</p>


<hr><h3><a name="decl_cvCreateSparseMat">CreateSparseMat</a></h3>
<p class="Blurb">Creates sparse array</p>
<pre>
CvSparseMat* cvCreateSparseMat( int dims, const int* sizes, int type );
</pre><p><dl>
<dt>dims<dd>Number of array dimensions. As opposite to the dense matrix, the number
            of dimensions is practically unlimited (up to 2<sup>16</sup>).
<dt>sizes<dd>Array of dimension sizes.
<dt>type<dd>Type of array elements. The same as for CvMat
</dl><p>
The function <code>cvCreateSparseMat</code> allocates multi-dimensional sparse array.
Initially the array contain no elements, that is <a href="#decl_cvGet*D">cvGet*D</a> or
<a href="#decl_cvGetReal*D">cvGetReal*D</a> return zero for every index</p>


<hr><h3><a name="decl_cvReleaseSparseMat">ReleaseSparseMat</a></h3>
<p class="Blurb">Deallocates sparse array</p>
<pre>
void cvReleaseSparseMat( CvSparseMat** mat );
</pre><p><dl>
<dt>mat<dd>Double pointer to the array.
</dl><p>
The function <code>cvReleaseSparseMat</code> releases the sparse array and clears the array pointer upon exit</p>


<hr><h3><a name="decl_cvCloneSparseMat">CloneSparseMat</a></h3>
<p class="Blurb">Creates full copy of sparse array</p>
<pre>
CvSparseMat* cvCloneSparseMat( const CvSparseMat* mat );
</pre><p><dl>
<dt>mat<dd>Input array.
</dl><p>
The function <code>cvCloneSparseMat</code> creates a copy of the input array and returns pointer to the copy.</p>


<hr><h2><a name="cxcore_arrays_get_set">Accessing Elements and sub-Arrays</a></h2>

<hr><h3><a name="decl_cvGetSubRect">GetSubRect</a></h3>
<p class="Blurb">Returns matrix header corresponding to the rectangular sub-array of input image or matrix</p>
<pre>
CvMat* cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>submat<dd>Pointer to the resultant sub-array header.
<dt>rect<dd>Zero-based coordinates of the rectangle of interest.
</dl><p>
The function <code>cvGetSubRect</code> returns header, corresponding
to a specified rectangle of the input array.
In other words, it allows the user to treat a rectangular part
of input array as a stand-alone array. ROI is taken into account by the function
so the sub-array of ROI is actually extracted.</p>


<hr><h3><a name="decl_cvGetRow">GetRow, GetRows</a></h3>
<p class="Blurb">Returns array row or row span</p>
<pre>
CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row );
CvMat* cvGetRows( const CvArr* arr, CvMat* submat, int start_row, int end_row, int delta_row=1 );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>submat<dd>Pointer to the resulting sub-array header.
<dt>row<dd>Zero-based index of the selected row.
<dt>start_row<dd>Zero-based index of the starting row (inclusive) of the span.
<dt>end_row<dd>Zero-based index of the ending row (exclusive) of the span.
<dt>delta_row<dd>Index step in the row span. That is, the function extracts every <code>delta_row</code>-th
row from <code>start_row</code> and up to (but not including) <code>end_row</code>.
</dl><p>
The functions <code>GetRow</code> and <code>GetRows</code> return the header, corresponding to a specified
row/row span of the input array. Note that <code>GetRow</code> is a shortcut for <a href="#decl_cvGetRows">cvGetRows</a>:
<pre>
cvGetRow( arr, submat, row ) ~ cvGetRows( arr, submat, row, row + 1, 1 );
</pre></p>


<hr><h3><a name="decl_cvGetCol">GetCol, GetCols</a></h3>
<p class="Blurb">Returns array column or column span</p>
<pre>
CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col );
CvMat* cvGetCols( const CvArr* arr, CvMat* submat, int start_col, int end_col );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>submat<dd>Pointer to the resulting sub-array header.
<dt>col<dd>Zero-based index of the selected column.
<dt>start_col<dd>Zero-based index of the starting column (inclusive) of the span.
<dt>end_col<dd>Zero-based index of the ending column (exclusive) of the span.
</dl><p>
The functions <code>GetCol</code> and <code>GetCols</code> return the header, corresponding to a specified
column/column span of the input array. Note that <code>GetCol</code> is a shortcut for <a href="#decl_cvGetCols">cvGetCols</a>:
<pre>
cvGetCol( arr, submat, col ); // ~ cvGetCols( arr, submat, col, col + 1 );
</pre></p>


<hr><h3><a name="decl_cvGetDiag">GetDiag</a></h3>
<p class="Blurb">Returns one of array diagonals</p>
<pre>
CvMat* cvGetDiag( const CvArr* arr, CvMat* submat, int diag=0 );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>submat<dd>Pointer to the resulting sub-array header.
<dt>diag<dd>Array diagonal. Zero corresponds to the main diagonal, -1 corresponds to the diagonal above
the main etc., 1 corresponds to the diagonal below the main etc.
</dl><p>
The function <code>cvGetDiag</code> returns the header, corresponding to a specified
diagonal of the input array.</p>


<hr><h3><a name="decl_cvGetSize">GetSize</a></h3>
<p class="Blurb">Returns size of matrix or image ROI</p>
<pre>
CvSize cvGetSize( const CvArr* arr );
</pre><p><dl>
<dt>arr<dd>array header.
</dl><p>
The function <code>cvGetSize</code> returns number of rows (CvSize::height) and number of columns
(CvSize::width) of the input matrix or image. In case of image the size of ROI is returned.</p>


<hr><h3><a name="decl_cvInitSparseMatIterator">InitSparseMatIterator</a></h3>
<p class="Blurb">Initializes sparse array elements iterator</p>
<pre>
CvSparseNode* cvInitSparseMatIterator( const CvSparseMat* mat,
                                       CvSparseMatIterator* mat_iterator );
</pre><p><dl>
<dt>mat<dd>Input array.
<dt>mat_iterator<dd>Initialized iterator.
</dl><p>
The function <code>cvInitSparseMatIterator</code> initializes iterator of sparse array elements and
returns pointer to the first element, or NULL if the array is empty.</p>


<hr><h3><a name="decl_cvGetNextSparseNode">GetNextSparseNode</a></h3>
<p class="Blurb">Initializes sparse array elements iterator</p>
<pre>
CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator );
</pre><p><dl>
<dt>mat_iterator<dd>Sparse array iterator.
</dl><p>
The function <code>cvGetNextSparseNode</code> moves iterator to the next sparse matrix element and returns
pointer to it. In the current version there is no any particular order of the elements, because they
are stored in hash table. The sample below demonstrates how to iterate through the sparse matrix:</p>
<p>
<font color=blue size=4>Using <a href="#decl_cvInitSparseMatIterator">cvInitSparseMatIterator</a> and <a href="#decl_cvGetNextSparseNode">cvGetNextSparseNode</a> to calculate sum of
floating-point sparse array.</font>
<pre>
    double sum;
    int i, dims = cvGetDims( array );
    CvSparseMatIterator mat_iterator;
    CvSparseNode* node = cvInitSparseMatIterator( array, &amp;mat_iterator );

    for( ; node != 0; node = cvGetNextSparseNode( &amp;mat_iterator ))
    {
        const int* idx = CV_NODE_IDX( array, node ); /* get pointer to the element indices */
        float val = *(float*)CV_NODE_VAL( array, node ); /* get value of the element
                                                          (assume that the type is CV_32FC1) */
        printf( "(" );
        for( i = 0; i &lt; dims; i++ )
            printf( "%4d%s", idx[i], i &lt; dims - 1 "," : "): " );
        printf( "%g\n", val );

        sum += val;
    }

    printf( "\nTotal sum = %g\n", sum );
</pre></p>

<hr><h3><a name="decl_cvGetElemType">GetElemType</a></h3>
<p class="Blurb">Returns type of array elements</p>
<pre>
int cvGetElemType( const CvArr* arr );
</pre><p><dl>
<dt>arr<dd>Input array.
</dl><p>
The functions <code>GetElemType</code> returns type of the array elements as it is described in
cvCreateMat discussion: <pre>CV_8UC1 ... CV_64FC4</pre></p>


<hr><h3><a name="decl_cvGetDims">GetDims, GetDimSize</a></h3>
<p class="Blurb">Return number of array dimensions and their sizes or the size of particular dimension</p>
<pre>
int cvGetDims( const CvArr* arr, int* sizes=NULL );
int cvGetDimSize( const CvArr* arr, int index );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>sizes<dd>Optional output vector of the array dimension sizes. For 2d arrays the number of rows (height)
goes first, number of columns (width) next.
<dt>index<dd>Zero-based dimension index (for matrices 0 means number of rows, 1 means number of columns;
for images 0 means height, 1 means width).
</dl><p>
The function <code>cvGetDims</code> returns number of array dimensions and their sizes.
In case of <code>IplImage</code> or <a href="#decl_CvMat">CvMat</a> it always returns 2 regardless of number of image/matrix rows.
The function <code>cvGetDimSize</code> returns the particular dimension size (number of elements per that dimension).
For example, the following code calculates total number of array elements in two ways:<pre>

// via cvGetDims()
int sizes[CV_MAX_DIM];
int i, total = 1;
int dims = cvGetDims( arr, size );
for( i = 0; i &lt; dims; i++ )
    total *= sizes[i];

// via cvGetDims() and cvGetDimSize()
int i, total = 1;
int dims = cvGetDims( arr );
for( i = 0; i &lt; dims; i++ )
    total *= cvGetDimsSize( arr, i );
</pre>
</p>


<hr><h3><a name="decl_cvPtr*D">Ptr*D</a></h3>
<p class="Blurb">Return pointer to the particular array element</p>
<pre>
uchar* cvPtr1D( const CvArr* arr, int idx0, int* type=NULL );
uchar* cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type=NULL );
uchar* cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, int* type=NULL );
uchar* cvPtrND( const CvArr* arr, const int* idx, int* type=NULL, int create_node=1, unsigned* precalc_hashval=NULL );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>idx0<dd>The first zero-based component of the element index
<dt>idx1<dd>The second zero-based component of the element index
<dt>idx2<dd>The third zero-based component of the element index
<dt>idx<dd>Array of the element indices
<dt>type<dd>Optional output parameter: type of matrix elements
<dt>create_node<dd>Optional input parameter for sparse matrices. Non-zero value of the parameter means that
the requested element is created if it does not exist already.
<dt>precalc_hashval<dd>Optional input parameter for sparse matrices. If the pointer is not NULL, the function
does not recalculate the node hash value, but takes it from the specified location. It is useful for speeding
up pair-wise operations (TODO: provide an example)
</dl><p>
The functions <code>>cvPtr*D</code> return pointer to the particular array element.
Number of array dimension should match to the number of indices passed to the function except
for <code>cvPtr1D</code> function that can be used for sequential access to 1D, 2D or nD dense arrays.
</p><p>
The functions can be used for sparse arrays as well - if the requested node does not exist they
create it and set it to zero.</p><p>
All these as well as other functions accessing array elements
(<a href="#decl_cvGet*D">cvGet*D</a>, <a href="#decl_cvGetReal*D">cvGetReal*D</a>,
<a href="#decl_cvSet*D">cvSet*D</a>, <a href="#decl_cvSetReal*D">cvSetReal*D</a>)
raise an error in case if the element index is out of range.
</p>


<hr><h3><a name="decl_cvGet*D">Get*D</a></h3>
<p class="Blurb">Return the particular array element</p>
<pre>
CvScalar cvGet1D( const CvArr* arr, int idx0 );
CvScalar cvGet2D( const CvArr* arr, int idx0, int idx1 );
CvScalar cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 );
CvScalar cvGetND( const CvArr* arr, const int* idx );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>idx0<dd>The first zero-based component of the element index
<dt>idx1<dd>The second zero-based component of the element index
<dt>idx2<dd>The third zero-based component of the element index
<dt>idx<dd>Array of the element indices
</dl><p>
The functions <code>cvGet*D</code> return the particular array element. In case of sparse array
the functions return 0 if the requested node does not exist (no new node is created
by the functions)</p>


<hr><h3><a name="decl_cvGetReal*D">GetReal*D</a></h3>
<p class="Blurb">Return the particular element of single-channel array</p>
<pre>
double cvGetReal1D( const CvArr* arr, int idx0 );
double cvGetReal2D( const CvArr* arr, int idx0, int idx1 );
double cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 );
double cvGetRealND( const CvArr* arr, const int* idx );
</pre><p><dl>
<dt>arr<dd>Input array. Must have a single channel.
<dt>idx0<dd>The first zero-based component of the element index
<dt>idx1<dd>The second zero-based component of the element index
<dt>idx2<dd>The third zero-based component of the element index
<dt>idx<dd>Array of the element indices
</dl><p>
The functions <code>cvGetReal*D</code> return the particular element of single-channel array.
If the array has multiple channels, runtime error is raised. Note that <a href="#decl_cvGet*D">cvGet*D</a> function
can be used safely for both single-channel and multiple-channel arrays though they are
a bit slower.</p><p>In case of sparse array
the functions return 0 if the requested node does not exist (no new node is created
by the functions)</p>


<hr><h3><a name="decl_cvmGet">mGet</a></h3>
<p class="Blurb">Return the particular element of single-channel floating-point matrix</p>
<pre>
double cvmGet( const CvMat* mat, int row, int col );
</pre><p><dl>
<dt>mat<dd>Input matrix.
<dt>row<dd>The zero-based index of row.
<dt>col<dd>The zero-based index of column.
</dl><p>
The function <code>cvmGet</code> is a fast replacement for <a href="#decl_cvGetReal2D">cvGetReal2D</a> in case of
single-channel floating-point matrices. It is faster because it is inline,
it does less checks for array type and array element type and it
checks for the row and column ranges only in debug mode.</p>


<hr><h3><a name="decl_cvSet*D">Set*D</a></h3>
<p class="Blurb">Change the particular array element</p>
<pre>
void cvSet1D( CvArr* arr, int idx0, CvScalar value );
void cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value );
void cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value );
void cvSetND( CvArr* arr, const int* idx, CvScalar value );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>idx0<dd>The first zero-based component of the element index
<dt>idx1<dd>The second zero-based component of the element index
<dt>idx2<dd>The third zero-based component of the element index
<dt>idx<dd>Array of the element indices
<dt>value<dd>The assigned value
</dl><p>
The functions <code>cvSet*D</code> assign the new value to the particular element of array.
In case of sparse array the functions create the node if it does not exist yet</p>


<hr><h3><a name="decl_cvSetReal*D">SetReal*D</a></h3>
<p class="Blurb">Change the particular array element</p>
<pre>
void cvSetReal1D( CvArr* arr, int idx0, double value );
void cvSetReal2D( CvArr* arr, int idx0, int idx1, double value );
void cvSetReal3D( CvArr* arr, int idx0, int idx1, int idx2, double value );
void cvSetRealND( CvArr* arr, const int* idx, double value );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>idx0<dd>The first zero-based component of the element index
<dt>idx1<dd>The second zero-based component of the element index
<dt>idx2<dd>The third zero-based component of the element index
<dt>idx<dd>Array of the element indices
<dt>value<dd>The assigned value
</dl><p>
The functions <code>cvSetReal*D</code> assign the new value to the particular element of single-channel array.
If the array has multiple channels, runtime error is raised. Note that <a href="#decl_cvSet*D">cvSet*D</a> function
can be used safely for both single-channel and multiple-channel arrays though they are
a bit slower.</p>
<p>In case of sparse array the functions create the node if it does not exist yet</p>


<hr><h3><a name="decl_cvmSet">mSet</a></h3>
<p class="Blurb">Return the particular element of single-channel floating-point matrix</p>
<pre>
void cvmSet( CvMat* mat, int row, int col, double value );
</pre><p><dl>
<dt>mat<dd>The matrix.
<dt>row<dd>The zero-based index of row.
<dt>col<dd>The zero-based index of column.
<dt>value<dd>The new value of the matrix element
</dl><p>
The function <code>cvmSet</code> is a fast replacement for <a href="#decl_cvSetReal2D">cvSetReal2D</a> in case of
single-channel floating-point matrices. It is faster because it is inline,
it does less checks for array type and array element type and it
checks for the row and column ranges only in debug mode.</p>


<hr><h3><a name="decl_cvClearND">ClearND</a></h3>
<p class="Blurb">Clears the particular array element</p>
<pre>
void cvClearND( CvArr* arr, const int* idx );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>idx<dd>Array of the element indices
</dl><p>
The function <a href="#decl_cvClearND">cvClearND</a> clears (sets to zero)
the particular element of dense array or deletes the element of sparse array.
If the element does not exists, the function does nothing.</p>


<hr><h2><a name="cxcore_arrays_copying">Copying and Filling</a></h2>


<hr><h3><a name="decl_cvCopy">Copy</a></h3>
<p class="Blurb">Copies one array to another</p>
<pre>
void cvCopy( const CvArr* src, CvArr* dst, const CvArr* mask=NULL );
</pre><p><dl>
<dt>src<dd>The source array.
<dt>dst<dd>The destination array.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function <code>cvCopy</code> copies selected elements from input array to output array:</p>
<p>
dst(I)=src(I) if mask(I)!=0.
</p><p>If any of the passed arrays is of <code>IplImage</code> type, then its ROI and COI fields are
used. Both arrays must have the same type, the same number of dimensions and the same size.
The function can also copy sparse arrays (mask is not supported in this case).</p>


<hr><h3><a name="decl_cvSet">Set</a></h3>
<p class="Blurb">Sets every element of array to given value</p>
<pre>
void cvSet( CvArr* arr, CvScalar value, const CvArr* mask=NULL );
</pre><p><dl>
<dt>arr<dd>The destination array.
<dt>value<dd>Fill value.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function <code>cvSet</code> copies scalar <code>value</code> to every selected element of the destination
array:</p>
<pre>arr(I)=value if mask(I)!=0</pre>
<p>If array <code>arr</code> is of <code>IplImage</code> type, then is ROI used, but COI must not be
set.</p>


<hr><h3><a name="decl_cvSetZero">SetZero</a></h3>
<p class="Blurb">Clears the array</p>
<pre>
void cvSetZero( CvArr* arr );
#define cvZero cvSetZero
</pre><p><dl>
<dt>arr<dd>array to be cleared.
</dl><p>
The function <code>cvSetZero</code> clears the array. In case of dense arrays
(CvMat, CvMatND or IplImage) cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0),
in case of sparse arrays all the elements are removed.</p>


<hr><h3><a name="decl_cvSetIdentity">SetIdentity</a></h3>
<p class="Blurb">Initializes scaled identity matrix</p>
<pre>
void cvSetIdentity( CvArr* mat, CvScalar value=cvRealScalar(1) );
</pre><p><dl>
<dt>arr<dd>The matrix to initialize (not necesserily square).
<dt>value<dd>The value to assign to the diagonal elements.
</dl><p>
The function <code>cvSetIdentity</code> initializes scaled identity matrix:</p>
<pre>
arr(i,j)=value if i=j,
       0 otherwise
</pre>


<hr><h3><a name="decl_cvRange">Range</a></h3>
<p class="Blurb">Fills matrix with given range of numbers</p>
<pre>
void cvRange( CvArr* mat, double start, double end );
</pre><p><dl>
<dt>mat<dd>The matrix to initialize. It should be single-channel 32-bit, integer or floating-point.
<dt>start<dd>The lower inclusive boundary of the range.
<dt>end<dd>The upper exclusive boundary of the range.
</dl><p>
The function <code>cvRange</code> initializes the matrix as following:</p>
<pre>
arr(i,j)=(end-start)*(i*cols(arr)+j)/(cols(arr)*rows(arr))
</pre>
For example, the following code will initilize 1D vector with subsequent integer numbers.
<pre>
CvMat* A = cvCreateMat( 1, 10, CV_32S );
cvRange( A, 0, A->cols ); // A will be initialized as [0,1,2,3,4,5,6,7,8,9]
</pre>

<!-- *****************************************************************************************
     *****************************************************************************************
     ***************************************************************************************** -->

<hr><h2><a name="cxcore_arrays_permute">Transforms and Permutations</a></h2>

<hr><h3><a name="decl_cvReshape">Reshape</a></h3>
<p class="Blurb">Changes shape of matrix/image without copying data</p>
<pre>
CvMat* cvReshape( const CvArr* arr, CvMat* header, int new_cn, int new_rows=0 );
</pre><p><dl>
<dt>arr<dd>Input array.
<dt>header<dd>Output header to be filled.
<dt>new_cn<dd>New number of channels. <code>new_cn = 0</code> means that number of channels remains unchanged.
<dt>new_rows<dd>New number of rows. <code>new_rows = 0</code> means that number of rows remains unchanged unless
it needs to be changed according to <code>new_cn</code> value.
destination array to be changed.
</dl><p>
The function <code>cvReshape</code> initializes CvMat header so that it points to the same data as
the original array but has different shape - different number of channels,
different number of rows or both.</p><p>For example, the following code creates one image buffer and
two image headers, first is for 320x240x3 image and the second is for 960x240x1 image:</p>
<pre>
IplImage* color_img = cvCreateImage( cvSize(320,240), IPL_DEPTH_8U, 3 );
CvMat gray_mat_hdr;
IplImage gray_img_hdr, *gray_img;
cvReshape( color_img, &amp;gray_mat_hdr, 1 );
gray_img = cvGetImage( &amp;gray_mat_hdr, &amp;gray_img_hdr );
</pre>
<p>And the next example converts 3x3 matrix to a single 1x9 vector</p>
<pre>
CvMat* mat = cvCreateMat( 3, 3, CV_32F );
CvMat row_header, *row;
row = cvReshape( mat, &amp;row_header, 0, 1 );
</pre>


<hr><h3><a name="decl_cvReshapeMatND">ReshapeMatND</a></h3>
<p class="Blurb">Changes shape of multi-dimensional array w/o copying data</p>
<pre>
CvArr* cvReshapeMatND( const CvArr* arr,
                       int sizeof_header, CvArr* header,
                       int new_cn, int new_dims, int* new_sizes );

#define cvReshapeND( arr, header, new_cn, new_dims, new_sizes )   \
      cvReshapeMatND( (arr), sizeof(*(header)), (header),         \
                      (new_cn), (new_dims), (new_sizes))

</pre><p><dl>
<dt>arr<dd>Input array.
<dt>sizeof_header<dd>Size of output header to distinguish between IplImage, CvMat and CvMatND output headers.
<dt>header<dd>Output header to be filled.
<dt>new_cn<dd>New number of channels. <code>new_cn = 0</code> means that number of channels remains unchanged.
<dt>new_dims<dd>New number of dimensions. <code>new_dims = 0</code> means that number of dimensions remains the same.
<dt>new_sizes<dd>Array of new dimension sizes. Only <code>new_dims-1</code> values are used, because the total number of
elements must remain the same. Thus, if <code>new_dims = 1</code>, <code>new_sizes</code> array is not used
</dl><p>
The function <code>cvReshapeMatND</code> is an advanced version of <a href="#decl_cvReshape">cvReshape</a> that can work
with multi-dimensional arrays as well (though, it can work with ordinary images and matrices)
and change the number of dimensions. Below are the two samples
from the <a href="#decl_cvReshape">cvReshape</a> description rewritten using <a href="#decl_cvReshapeMatND">cvReshapeMatND</a>:</p>
<pre>
IplImage* color_img = cvCreateImage( cvSize(320,240), IPL_DEPTH_8U, 3 );
IplImage gray_img_hdr, *gray_img;
gray_img = (IplImage*)cvReshapeND( color_img, &amp;gray_img_hdr, 1, 0, 0 );

...

/* second example is modified to convert 2x2x2 array to 8x1 vector */
int size[] = { 2, 2, 2 };
CvMatND* mat = cvCreateMatND( 3, size, CV_32F );
CvMat row_header, *row;
row = cvReshapeND( mat, &amp;row_header, 0, 1, 0 );
</pre>


<hr><h3><a name="decl_cvRepeat">Repeat</a></h3>
<p class="Blurb">Fill destination array with tiled source array</p>
<pre>
void cvRepeat( const CvArr* src, CvArr* dst );
</pre><p><dl>
<dt>src<dd>Source array, image or matrix.
<dt>dst<dd>Destination array, image or matrix.
</dl><p>
The function <code>cvRepeat</code> fills the destination array with source array tiled:</p>
<pre>dst(i,j)=src(i mod rows(src), j mod cols(src))</pre>
<p>
So the destination array may be as larger as well as smaller than
the source array.
</p>


<hr><h3><a name="decl_cvFlip">Flip</a></h3>
<p class="Blurb">Flip a 2D array around vertical, horizontall or both axises</p>
<pre>
void  cvFlip( const CvArr* src, CvArr* dst=NULL, int flip_mode=0);
#define cvMirror cvFlip

</pre><p><dl>
<dt>src<dd>Source array.
<dt>dst<dd>Destination array. If <code>dst = NULL</code> the flipping is done inplace.
<dt>flip_mode<dd>Specifies how to flip the array.<br>
                 flip_mode = 0 means flipping around x-axis,
                 flip_mode > 0 (e.g. 1) means flipping around y-axis
                 and flip_mode &lt; 0 (e.g. -1) means flipping around both axises.
                 See also the discussion below for the formulas
</dl><p>
The function <code>cvFlip</code> flips the array in one of different 3 ways
(row and column indices are 0-based):</p>
<pre>dst(i,j)=src(rows(src)-i-1,j) if flip_mode = 0</pre>
<pre>dst(i,j)=src(i,cols(src1)-j-1) if flip_mode > 0</pre>
<pre>dst(i,j)=src(rows(src)-i-1,cols(src)-j-1) if flip_mode &lt; 0</pre>
<p>The example cenaria of the function use are:
<ul>
<li>
vertical flipping of the image (flip_mode > 0) to switch between top-left
and bottom-left image origin, which is typical operation in video processing under Win32 systems.</li>
<li>
horizontal flipping of the image with subsequent horizontal shift and absolute difference calculation
to check for a vertical-axis symmetry (flip_mode > 0)</li>
<li>
simultaneous horizontal and vertical flipping of the image with subsequent shift and
absolute difference calculation to check for a central symmetry (flip_mode &lt; 0)</li>
<li>reversing the order of 1d point arrays(flip_mode > 0)</li>
</ul></p>


<hr><h3><a name="decl_cvSplit">Split</a></h3>
<p class="Blurb">Divides multi-channel array into several single-channel arrays or extracts
a single channel from the array</p>
<pre>
void cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1,
              CvArr* dst2, CvArr* dst3 );
#define cvCvtPixToPlane cvSplit
</pre><p><dl>
<dt>src<dd>Source array.
<dt>dst0...dst3<dd>Destination channels.
</dl><p>
The function <code>cvSplit</code> divides a multi-channel array into separate single-channel arrays.
Two modes are available for the operation. If the source array has N channels then if
the first N destination channels are not NULL, all they are extracted from the source array,
otherwise if only a single destination channel of the first N is not NULL, this particular channel
is extracted, otherwise an error is raised. Rest of destination channels (beyond the first N)
must always be NULL.
For IplImage <a href="#decl_cvCopy">cvCopy</a> with COI set can be also used to extract a single channel from the image.</p>


<hr><h3><a name="decl_cvMerge">Merge</a></h3>
<p class="Blurb">Composes multi-channel array from several single-channel arrays or inserts a
single channel into the array</p>
<pre>
void cvMerge( const CvArr* src0, const CvArr* src1,
              const CvArr* src2, const CvArr* src3, CvArr* dst );
#define cvCvtPlaneToPix cvMerge
</pre><p><dl>
<dt>src0... src3<dd>Input channels.
<dt>dst<dd>Destination array.
</dl><p>
The function <code>cvMerge</code> is the opposite to the previous.
If the destination array has N channels then if
the first N input channels are not NULL, all they are copied to the destination array,
otherwise if only a single source channel of the first N is not NULL, this particular channel is copied
into the destination array, otherwise an error is raised. Rest of source channels (beyond the first N)
must always be NULL.
For IplImage <a href="#decl_cvCopy">cvCopy</a> with COI set can be also used to insert a single channel into the image.
</p>


<hr><h3><a name="decl_cvMixChannels">MixChannels</a></h3>
<p class="Blurb">Copies several channels from input arrays to
   certain channels of output arrays</p>
<pre>
void cvMixChannels( const CvArr** src, int src_count,
                    CvArr** dst, int dst_count,
                    const int* from_to, int pair_count );
</pre><p><dl>
<dt>src<dd>The array of input arrays.
<dt>src_count<dd>The number of input arrays.
<dt>dst<dd>The array of output arrays.
<dt>dst_count<dd>The number of output arrays.
<dt>from_to<dd>The array of pairs of indices of the planes copied.
<code>from_to[k*2]</code> is the 0-based index of the input plane,
and <code>from_to[k*2+1]</code> is the index of the output plane, where the continuous numbering
of the planes over all the input and over all the output arrays is used.
When <code>from_to[k*2]</code> is negative, the corresponding output plane is filled with 0's.
<dt>pair_count<dd>The number of pairs in <code>from_to</code>, or the number of the planes copied.
</dl><p>
The function <code>cvMixChannels</code> is a generalized form of <a href="#decl_cvSplit">cvSplit</a> and
<a href="#decl_cvMerge">cvMerge</a> and some forms of <a href="opencvref_cv.htm#decl_cvCvtColor">cvCvtColor</a>.
It can be used to change the order of the planes, add/remove alpha
channel, extract or insert a single plane or multiple planes etc.
Below is the example, how to split 4-channel RGBA image into 3-channel BGR (i.e. with R&B swapped) and
separate alpha channel images:</p>
<pre>
    CvMat* rgba = cvCreateMat( 100, 100, CV_8UC4 );
    CvMat* bgr = cvCreateMat( rgba->rows, rgba->cols, CV_8UC3 );
    CvMat* alpha = cvCreateMat( rgba->rows, rgba->cols, CV_8UC1 );
    CvArr* out[] = { bgr, alpha };
    int from_to[] = { 0, 2, 1, 1, 2, 0, 3, 3 };
    cvSet( rgba, cvScalar(1,2,3,4) );
    cvMixChannels( (const CvArr**)&rgba, 1, out, 2, from_to, 4 );
</pre>


<hr><h3><a name="decl_cvRandShuffle">RandShuffle</a></h3>
<p class="Blurb">Randomly shuffles the array elements</p>
<pre>
void cvRandShuffle( CvArr* mat, CvRNG* rng, double iter_factor=1. );
</pre><p><dl>
<dt>mat<dd>The input/output matrix. It is shuffled in-place.
<dt>rng<dd>The <a href="#cxcore_arrays_rng">Random Number Generator</a>
           used to shuffle the elements. When the pointer is NULL,
           a temporary RNG will be created and used.
<dt>iter_factor<dd>The relative parameter that characterizes intensity of the shuffling performed.
                   See the description below.
</dl><p>
The function <code>cvRandShuffle</code> shuffles the matrix by swapping randomly chosen pairs
of the matrix elements on each iteration (where each element may contain several components in case of multi-channel arrays).
The number of iterations (i.e. pairs swapped) is <code>round(iter_factor*rows(mat)*cols(mat))</code>, so
<code>iter_factor=0</code> means that no shuffling is done,
<code>iter_factor=1</code> means that the function swaps
<code>rows(mat)*cols(mat)</code> random pairs etc.
</p>


<hr><h2><a name="cxcore_arrays_arithm_logic">Arithmetic, Logic and Comparison</a></h2>


<hr><h3><a name="decl_cvLUT">LUT</a></h3>
<p class="Blurb">Performs look-up table transform of array</p>
<pre>
void cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut );
</pre><p><dl>
<dt>src<dd>Source array of 8-bit elements.
<dt>dst<dd>Destination array of arbitrary depth and of the same number of channels as the
source array.
<dt>lut<dd>Look-up table of 256 elements; should have the same depth as the
destination array. In case of multi-channel source and destination arrays, the table
should either have a single-channel (in this case the same table is used for all channels),
or the same number of channels as the source/destination array.
</dl><p>
The function <code>cvLUT</code> fills the destination array with values
from the look-up table. Indices of the entries are taken from the source array. That is, the
function processes each element of <code>src</code> as following:</p>
<pre>
dst(I)=lut[src(I)+DELTA]
</pre>
where <code>DELTA=0</code> if <code>src</code> has depth <code>CV_8U</code>, and
<code>DELTA=128</code> if <code>src</code> has depth <code>CV_8S</code>.
</p>


<hr><h3><a name="decl_cvConvertScale">ConvertScale</a></h3>
<p class="Blurb">Converts one array to another with optional linear transformation</p>
<pre>
void cvConvertScale( const CvArr* src, CvArr* dst, double scale=1, double shift=0 );

#define cvCvtScale cvConvertScale
#define cvScale  cvConvertScale
#define cvConvert( src, dst )  cvConvertScale( (src), (dst), 1, 0 )
</pre><p><dl>
<dt>src<dd>Source array.
<dt>dst<dd>Destination array.
<dt>scale<dd>Scale factor.
<dt>shift<dd>Value added to the scaled source array elements.
</dl><p>
The function <code>cvConvertScale</code> has several different purposes and thus has several synonyms.
It copies one array to another with optional scaling, which is performed first, and/or optional type conversion, performed after:</p>
<pre>dst(I)=src(I)*scale + (shift,shift,...)</pre>
<p>All the channels of multi-channel arrays are processed independently.</p><p>
The type conversion is done with rounding and saturation, that is if a result of scaling + conversion can not
be represented exactly by a value of destination array element type, it is set to the nearest
representable value on the real axis.</p>
<p>In case of <code>scale=1, shift=0</code> no prescaling is done. This is a specially optimized case and it
has the appropriate <a href="#decl_cvConvert">cvConvert</a> synonym. If source and destination array types have
equal types, this is also a special case that can be used to scale and shift a matrix or an image and
that fits to <a href="#decl_cvScale">cvScale</a> synonym.</p>


<hr><h3><a name="decl_cvConvertScaleAbs">ConvertScaleAbs</a></h3>
<p class="Blurb">Converts input array elements to 8-bit unsigned integer another with optional linear transformation</p>
<pre>
void cvConvertScaleAbs( const CvArr* src, CvArr* dst, double scale=1, double shift=0 );
#define cvCvtScaleAbs cvConvertScaleAbs

</pre><p><dl>
<dt>src<dd>Source array.
<dt>dst<dd>Destination array (should have 8u depth).
<dt>scale<dd>ScaleAbs factor.
<dt>shift<dd>Value added to the scaled source array elements.
</dl><p>
The function <code>cvConvertScaleAbs</code> is similar to the previous one, but it stores absolute values
of the conversion results:</p>
<pre>dst(I)=abs(src(I)*scale + (shift,shift,...))</pre>
<p>
The function supports only destination arrays of 8u (8-bit unsigned integers) type, for
other types the function can be emulated by combination of <a href="#decl_cvConvertScale">cvConvertScale</a> and <a href="#decl_cvAbsDiffS">cvAbs</a>
functions.</p>


<hr><h3><a name="decl_cvAdd">Add</a></h3>
<p class="Blurb">Computes per-element sum of two arrays</p>
<pre>
void cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
</pre><p><dl>

<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array.
<dt>dst<dd>The destination array.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function <code>cvAdd</code> adds one array to another one:</p>
<pre>dst(I)=src1(I)+src2(I) if mask(I)!=0</pre>
<p>All the arrays must have the same type, except the mask, and the same size (or ROI size)</p>


</p><hr><h3><a name="decl_cvAddS">AddS</a></h3>
<p class="Blurb">Computes sum of array and scalar</p>
<pre>
void cvAddS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
</pre><p><dl>
<dt>src<dd>The source array.
<dt>value<dd>Added scalar.
<dt>dst<dd>The destination array.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function <code>cvAddS</code> adds scalar <code>value</code> to every element in the source array <code>src1</code> and
stores the result in <code>dst</code><p>
<pre>dst(I)=src(I)+value if mask(I)!=0</pre>
<p>All the arrays must have the same type, except the mask, and the same size (or ROI size)</p>


<hr><h3><a name="decl_cvAddWeighted">AddWeighted</a></h3>
<p class="Blurb">Computes weighted sum of two arrays</p>
<pre>
void  cvAddWeighted( const CvArr* src1, double alpha,
                     const CvArr* src2, double beta,
                     double gamma, CvArr* dst );
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>alpha<dd>Weight of the first array elements.
<dt>src2<dd>The second source array.
<dt>beta<dd>Weight of the second array elements.
<dt>dst<dd>The destination array.
<dt>gamma<dd>Scalar, added to each sum.
</dl><p>
The function <code>cvAddWeighted</code> calculated weighted sum
of two arrays as following:</p>
<pre>dst(I)=src1(I)*alpha+src2(I)*beta+gamma</pre>
<p>All the arrays must have the same type and the same size (or ROI size)</p>


<hr><h3><a name="decl_cvSub">Sub</a></h3>
<p class="Blurb">Computes per-element difference between two arrays</p>
<pre>
void cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array.
<dt>dst<dd>The destination array.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function <code>cvSub</code> subtracts one array from another one:</p>
<pre>dst(I)=src1(I)-src2(I) if mask(I)!=0</pre>
<p>All the arrays must have the same type, except the mask, and the same size (or ROI size)</p>


</p><hr><h3><a name="decl_cvSubS">SubS</a></h3>
<p class="Blurb">Computes difference between array and scalar</p>
<pre>
void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
</pre><p><dl>
<dt>src<dd>The source array.
<dt>value<dd>Subtracted scalar.
<dt>dst<dd>The destination array.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function <code>cvSubS</code> subtracts a scalar from every element of the source array:<p>
<pre>dst(I)=src(I)-value if mask(I)!=0</pre>
<p>All the arrays must have the same type, except the mask, and the same size (or ROI size)</p>


<hr><h3><a name="decl_cvSubRS">SubRS</a></h3>
<p class="Blurb">Computes difference between scalar and array</p>
<pre>
void cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
</pre><p><dl>
<dt>src<dd>The first source array.
<dt>value<dd>Scalar to subtract from.
<dt>dst<dd>The destination array.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function <code>cvSubRS</code> subtracts every element of source array from a scalar:</p>
<pre>dst(I)=value-src(I) if mask(I)!=0</pre>
<p>All the arrays must have the same type, except the mask, and the same size (or ROI size)</p>


<hr><h3><a name="decl_cvMul">Mul</a></h3>
<p class="Blurb">Calculates per-element product of two arrays</p>
<pre>
void cvMul( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array.
<dt>dst<dd>The destination array.
<dt>scale<dd>Optional scale factor
</dl><p>
The function <code>cvMul</code> calculates per-element product of two arrays:</p>
<pre>dst(I)=scale&bull;src1(I)&bull;src2(I)</pre>
<p>All the arrays must have the same type, and the same size (or ROI size)</p>


<hr><h3><a name="decl_cvDiv">Div</a></h3>
<p class="Blurb">Performs per-element division of two arrays</p>
<pre>
void cvDiv( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );
</pre><p><dl>
<dt>src1<dd>The first source array. If the pointer is NULL, the array is assumed to be all 1&#146;s.
<dt>src2<dd>The second source array.
<dt>dst<dd>The destination array.
<dt>scale<dd>Optional scale factor
</dl><p>
The function <code>cvDiv</code> divides one array by another:</p>
<pre>
dst(I)=scale&bull;src1(I)/src2(I), if src1!=NULL
dst(I)=scale/src2(I),      if src1=NULL
</pre>
<p>All the arrays must have the same type, and the same size (or ROI size)</p>


<hr><h3><a name="decl_cvAnd">And</a></h3>
<p class="Blurb">Calculates per-element bit-wise conjunction of two arrays</p>
<pre>
void cvAnd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array.
<dt>dst<dd>The destination array.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function <code>cvAnd</code> calculates per-element bit-wise logical conjunction of two arrays:</p>
<pre>dst(I)=src1(I)&amp;src2(I) if mask(I)!=0</pre>
<p>In the case of floating-point arrays their bit representations are used for the
operation. All the arrays must have the same type, except the mask, and the same size</p>


<hr><h3><a name="decl_cvAndS">AndS</a></h3>
<p class="Blurb">Calculates per-element bit-wise conjunction of array and scalar</p>
<pre>
void cvAndS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
</pre><p><dl>
<dt>src<dd>The source array.
<dt>value<dd>Scalar to use in the operation.
<dt>dst<dd>The destination array.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function AndS calculates per-element bit-wise conjunction of array and scalar:</p>
<pre>dst(I)=src(I)&amp;value if mask(I)!=0</pre>
<p>Prior to the actual operation the scalar is converted to the same type as
the arrays. In the case of floating-point arrays their bit representations are used for the
operation. All the arrays must have the same type, except the mask, and the same size</p>

<p>The following sample demonstrates how to calculate absolute value of floating-point array elements
by clearing the most-significant bit:</p>
<pre>
float a[] = { -1, 2, -3, 4, -5, 6, -7, 8, -9 };
CvMat A = cvMat( 3, 3, CV_32F, &amp;a );
int i, abs_mask = 0x7fffffff;
cvAndS( &amp;A, cvRealScalar(*(float*)&amp;abs_mask), &amp;A, 0 );
for( i = 0; i &lt; 9; i++ )
    printf("%.1f ", a[i] );
</pre>
<p>The code should print:</p>
<pre>1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0</pre>


<hr><h3><a name="decl_cvOr">Or</a></h3>
<p class="Blurb">Calculates per-element bit-wise disjunction of two arrays</p>
<pre>
void cvOr( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array.
<dt>dst<dd>The destination array.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function <code>cvOr</code> calculates per-element bit-wise disjunction of two arrays:</p>
<pre>dst(I)=src1(I)|src2(I)</pre>
<p>In the case of floating-point arrays their bit representations are used for the
operation. All the arrays must have the same type, except the mask, and the same size</p>


<hr><h3><a name="decl_cvOrS">OrS</a></h3>
<p class="Blurb">Calculates per-element bit-wise disjunction of array and scalar</p>
<pre>
void cvOrS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
</pre><p><dl>
<dt>src1<dd>The source array.
<dt>value<dd>Scalar to use in the operation.
<dt>dst<dd>The destination array.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function OrS calculates per-element bit-wise disjunction of array and scalar:</p>
<pre>dst(I)=src(I)|value if mask(I)!=0</pre>
<p>Prior to the actual operation the scalar is converted to the same type as
the arrays. In the case of floating-point arrays their bit representations are used for the
operation. All the arrays must have the same type, except the mask, and the same size</p>


<hr><h3><a name="decl_cvXor">Xor</a></h3>
<p class="Blurb">Performs per-element bit-wise "exclusive or" operation on two arrays</p>
<pre>
void cvXor( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array.
<dt>dst<dd>The destination array.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function <code>cvXor</code> calculates per-element bit-wise logical conjunction of two arrays:</p>
<pre>dst(I)=src1(I)^src2(I) if mask(I)!=0</pre>
<p>In the case of floating-point arrays their bit representations are used for the
operation. All the arrays must have the same type, except the mask, and the same size</p>


<hr><h3><a name="decl_cvXorS">XorS</a></h3>
<p class="Blurb">Performs per-element bit-wise "exclusive or" operation on array and scalar</p>
<pre>
void cvXorS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
</pre><p><dl>
<dt>src<dd>The source array.
<dt>value<dd>Scalar to use in the operation.
<dt>dst<dd>The destination array.
<dt>mask<dd>Operation mask, 8-bit single channel array; specifies elements of
destination array to be changed.
</dl><p>
The function XorS calculates per-element bit-wise conjunction of array and scalar:</p>
<pre>dst(I)=src(I)^value if mask(I)!=0</pre>
<p>Prior to the actual operation the scalar is converted to the same type as
the arrays. In the case of floating-point arrays their bit representations are used for the
operation. All the arrays must have the same type, except the mask, and the same size</p>

<p>The following sample demonstrates how to conjugate complex vector
by switching the most-significant bit of imaging part:</p>
<pre>
float a[] = { 1, 0, 0, 1, -1, 0, 0, -1 }; /* 1, j, -1, -j */
CvMat A = cvMat( 4, 1, CV_32FC2, &amp;a );
int i, neg_mask = 0x80000000;
cvXorS( &amp;A, cvScalar( 0, *(float*)&amp;neg_mask, 0, 0 ), &amp;A, 0 );
for( i = 0; i &lt; 4; i++ )
    printf("(%.1f, %.1f) ", a[i*2], a[i*2+1] );
</pre>
<p>The code should print:</p>
<pre>(1.0,0.0) (0.0,-1.0) (-1.0,0.0) (0.0,1.0)</pre>


<hr><h3><a name="decl_cvNot">Not</a></h3>
<p class="Blurb">Performs per-element bit-wise inversion of array elements</p>
<pre>
void cvNot( const CvArr* src, CvArr* dst );
</pre><p><dl>
<dt>src1<dd>The source array.
<dt>dst<dd>The destination array.
</dl><p>
The function Not inverses every bit of every array element:</p>
<pre>dst(I)=~src(I)</pre>


<hr><h3><a name="decl_cvCmp">Cmp</a></h3>
<p class="Blurb">Performs per-element comparison of two arrays</p>
<pre>
void cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op );
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array. Both source array must have a single channel.
<dt>dst<dd>The destination array, must have 8u or 8s type.
<dt>cmp_op<dd>The flag specifying the relation between the elements to be checked:<br>
              CV_CMP_EQ - src1(I) "equal to" src2(I)<br>
              CV_CMP_GT - src1(I) "greater than" src2(I)<br>
              CV_CMP_GE - src1(I) "greater or equal" src2(I)<br>
              CV_CMP_LT - src1(I) "less than" src2(I)<br>
              CV_CMP_LE - src1(I) "less or equal" src2(I)<br>
              CV_CMP_NE - src1(I) "not equal to" src2(I)<br>
</dl><p>
The function <code>cvCmp</code> compares the corresponding elements of two arrays and
fills the destination mask array:</p>
<pre>
dst(I)=src1(I) op src2(I),
</pre>
<p>where <code>op</code> is '=', '&gt;', '&gt;=', '&lt;', '&lt;=' or '!='.</p>
<p><code>dst(I)</code> is set to 0xff (all '1'-bits) if the particular relation between the elements
is true and 0 otherwise.
All the arrays must have the same type, except the destination, and the same size (or ROI size)</p>


<hr><h3><a name="decl_cvCmpS">CmpS</a></h3>
<p class="Blurb">Performs per-element comparison of array and scalar</p>
<pre>
void cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op );
</pre><p><dl>
<dt>src<dd>The source array, must have a single channel.
<dt>value<dd>The scalar value to compare each array element with.
<dt>dst<dd>The destination array, must have 8u or 8s type.
<dt>cmp_op<dd>The flag specifying the relation between the elements to be checked:<br>
              CV_CMP_EQ - src1(I) "equal to" value<br>
              CV_CMP_GT - src1(I) "greater than" value<br>
              CV_CMP_GE - src1(I) "greater or equal" value<br>
              CV_CMP_LT - src1(I) "less than" value<br>
              CV_CMP_LE - src1(I) "less or equal" value<br>
              CV_CMP_NE - src1(I) "not equal" value<br>
</dl><p>
The function <code>cvCmpS</code> compares the corresponding elements of array and scalar
and fills the destination mask array:</p>
<pre>
dst(I)=src(I) op scalar,
</pre>
<p>where <code>op</code> is '=', '&gt;', '&gt;=', '&lt;', '&lt;=' or '!='.</p>
<p><code>dst(I)</code> is set to 0xff (all '1'-bits) if the particular relation between the elements
is true and 0 otherwise.
All the arrays must have the same size (or ROI size)</p>



<hr><h3><a name="decl_cvInRange">InRange</a></h3>
<p class="Blurb">Checks that array elements lie between elements of two other arrays</p>
<pre>
void cvInRange( const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst );
</pre><p><dl>
<dt>src<dd>The first source array.
<dt>lower<dd>The inclusive lower boundary array.
<dt>upper<dd>The exclusive upper boundary array.
<dt>dst<dd>The destination array, must have 8u or 8s type.
</dl><p>
The function <code>cvInRange</code> does the range check for every element of the input array:</p>
<pre>
dst(I)=lower(I)<sub>0</sub> &lt;= src(I)<sub>0</sub> &lt; upper(I)<sub>0</sub>
</pre>
<p>for single-channel arrays,</p>
<pre>
dst(I)=lower(I)<sub>0</sub> &lt;= src(I)<sub>0</sub> &lt; upper(I)<sub>0</sub> &amp;&amp;
     lower(I)<sub>1</sub> &lt;= src(I)<sub>1</sub> &lt; upper(I)<sub>1</sub>
</pre><p>for two-channel arrays etc.</p>
<p><code>dst(I)</code> is set to 0xff (all '1'-bits) if <code>src(I)</code> is within the range and 0 otherwise.
All the arrays must have the same type, except the destination, and the same size (or ROI size)</p>


<hr><h3><a name="decl_cvInRangeS">InRangeS</a></h3>
<p class="Blurb">Checks that array elements lie between two scalars</p>
<pre>
void cvInRangeS( const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst );
</pre><p><dl>
<dt>src<dd>The first source array.
<dt>lower<dd>The inclusive lower boundary.
<dt>upper<dd>The exclusive upper boundary.
<dt>dst<dd>The destination array, must have 8u or 8s type.
</dl><p>
The function <code>cvInRangeS</code> does the range check for every element of the input array:</p>
<pre>
dst(I)=lower<sub>0</sub> &lt;= src(I)<sub>0</sub> &lt; upper<sub>0</sub>
</pre>
<p>for a single-channel array,</p>
<pre>
dst(I)=lower<sub>0</sub> &lt;= src(I)<sub>0</sub> &lt; upper<sub>0</sub> &amp;&amp;
     lower<sub>1</sub> &lt;= src(I)<sub>1</sub> &lt; upper<sub>1</sub>
</pre><p>for a two-channel array etc.</p>
<p>
<p><code>dst(I)</code> is set to 0xff (all '1'-bits) if <code>src(I)</code> is within the range and 0 otherwise.
All the arrays must have the same size (or ROI size)</p>


<hr><h3><a name="decl_cvMax">Max</a></h3>
<p class="Blurb">Finds per-element maximum of two arrays</p>
<pre>
void cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst );
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array.
<dt>dst<dd>The destination array.
</dl><p>
The function <code>cvMax</code> calculates per-element maximum of two arrays:</p>
<pre>dst(I)=max(src1(I), src2(I))</pre>
<p>All the arrays must have a single channel, the same data type
and the same size (or ROI size).</p>


<hr><h3><a name="decl_cvMaxS">MaxS</a></h3>
<p class="Blurb">Finds per-element maximum of array and scalar</p>
<pre>
void cvMaxS( const CvArr* src, double value, CvArr* dst );
</pre><p><dl>
<dt>src<dd>The first source array.
<dt>value<dd>The scalar value.
<dt>dst<dd>The destination array.
</dl><p>
The function <code>cvMaxS</code> calculates per-element maximum of array and scalar:</p>
<pre>dst(I)=max(src(I), value)</pre>
<p>All the arrays must have a single channel, the same data type
and the same size (or ROI size).</p>


<hr><h3><a name="decl_cvMin">Min</a></h3>
<p class="Blurb">Finds per-element minimum of two arrays</p>
<pre>
void cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst );
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array.
<dt>dst<dd>The destination array.
</dl><p>
The function <code>cvMin</code> calculates per-element minimum of two arrays:</p>
<pre>
dst(I)=min(src1(I),src2(I))
</pre>
<p>All the arrays must have a single channel, the same data type
and the same size (or ROI size).</p>



<hr><h3><a name="decl_cvMinS">MinS</a></h3>
<p class="Blurb">Finds per-element minimum of array and scalar</p>
<pre>
void cvMinS( const CvArr* src, double value, CvArr* dst );
</pre><p><dl>
<dt>src<dd>The first source array.
<dt>value<dd>The scalar value.
<dt>dst<dd>The destination array.
</dl><p>
The function <code>cvMinS</code> calculates minimum of array and scalar:</p>
<pre>dst(I)=min(src(I), value)</pre>
<p>All the arrays must have a single channel, the same data type
and the same size (or ROI size).</p>


<hr><h3><a name="decl_cvAbsDiff">AbsDiff</a></h3>
<p class="Blurb">Calculates absolute difference between two arrays</p>
<pre>
void cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst );
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array.
<dt>dst<dd>The destination array.
</dl><p>
The function <code>cvAbsDiff</code> calculates absolute difference between two arrays.</p>
<pre>dst(I)<sub>c</sub> = abs(src1(I)<sub>c</sub> - src2(I)<sub>c</sub>).</pre>
<p>All the arrays must have the same data type and the same size (or ROI size).</p>


<hr><h3><a name="decl_cvAbsDiffS">AbsDiffS</a></h3>
<p class="Blurb">Calculates absolute difference between array and scalar</p>
<pre>
void cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value );
#define cvAbs(src, dst) cvAbsDiffS(src, dst, cvScalarAll(0))
</pre><p><dl>
<dt>src<dd>The source array.
<dt>dst<dd>The destination array.
<dt>value<dd>The scalar.
</dl><p>
The function <code>cvAbsDiffS</code> calculates absolute difference between array and scalar.</p>
<pre>dst(I)<sub>c</sub> = abs(src(I)<sub>c</sub> - value<sub>c</sub>).</pre>
<p>All the arrays must have the same data type and the same size (or ROI size).</p>


<hr><h2><a name="cxcore_arrays_stat">Statistics</a></h2>

<hr><h3><a name="decl_cvCountNonZero">CountNonZero</a></h3>
<p class="Blurb">Counts non-zero array elements</p>
<pre>
int cvCountNonZero( const CvArr* arr );
</pre><p><dl>
<dt>arr<dd>The array, must be single-channel array or multi-channel image with COI set.
</dl><p>
The function <code>cvCountNonZero</code> returns the number of non-zero elements in src1:</p>
<pre>
result = sum<sub>I</sub> arr(I)!=0
</pre>
In case of <code>IplImage</code> both ROI and COI are supported.</p>


<hr><h3><a name="decl_cvSum">Sum</a></h3>
<p class="Blurb">Summarizes array elements</p>
<pre>
CvScalar cvSum( const CvArr* arr );
</pre><p><dl>
<dt>arr<dd>The array.
</dl><p>
The function <code>cvSum</code> calculates sum <code>S</code> of array elements, independently for each channel:</p>
<pre>
S<sub>c</sub> = sum<sub>I</sub> arr(I)<sub>c</sub>
</pre>
If the array is <code>IplImage</code> and COI is set, the function processes the selected channel only
and stores the sum to the first scalar component (S<sub>0</sub>).</p>


<hr><h3><a name="decl_cvAvg">Avg</a></h3>
<p class="Blurb">Calculates average (mean) of array elements</p>
<pre>
CvScalar cvAvg( const CvArr* arr, const CvArr* mask=NULL );
</pre><p><dl>
<dt>arr<dd>The array.
<dt>mask<dd>The optional operation mask.
</dl><p>
The function <code>cvAvg</code> calculates the average value <code>M</code> of array elements, independently for each channel:</p>
<pre>
N = sum<sub>I</sub> mask(I)!=0

M<sub>c</sub> = 1/N &bull; sum<sub>I,mask(I)!=0</sub> arr(I)<sub>c</sub>
</pre>
If the array is <code>IplImage</code> and COI is set, the function processes the selected channel only
and stores the average to the first scalar component (S<sub>0</sub>).</p>


<hr><h3><a name="decl_cvAvgSdv">AvgSdv</a></h3>
<p class="Blurb">Calculates average (mean) of array elements</p>
<pre>
void cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev, const CvArr* mask=NULL );
</pre><p><dl>
<dt>arr<dd>The array.
<dt>mean<dd>Pointer to the mean value, may be NULL if it is not needed.
<dt>std_dev<dd>Pointer to the standard deviation.
<dt>mask<dd>The optional operation mask.
</dl><p>
The function <code>cvAvgSdv</code> calculates the average value and
standard deviation of array elements, independently for each channel:</p>
<pre>
N = sum<sub>I</sub> mask(I)!=0

mean<sub>c</sub> = 1/N &bull; sum<sub>I,mask(I)!=0</sub> arr(I)<sub>c</sub>

std_dev<sub>c</sub> = sqrt(1/N &bull; sum<sub>I,mask(I)!=0</sub> (arr(I)<sub>c</sub> - M<sub>c</sub>)<sup>2</sup>)
</pre>
If the array is <code>IplImage</code> and COI is set, the function processes the selected channel only
and stores the average and standard deviation to the first compoenents of output scalars (M<sub>0</sub>
and S<sub>0</sub>).</p>



<hr><h3><a name="decl_cvMinMaxLoc">MinMaxLoc</a></h3>
<p class="Blurb">Finds global minimum and maximum in array or subarray</p>
<pre>
void cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val,
                  CvPoint* min_loc=NULL, CvPoint* max_loc=NULL, const CvArr* mask=NULL );
</pre><p><dl>
<dt>arr<dd>The source array, single-channel or multi-channel with COI set.
<dt>min_val<dd>Pointer to returned minimum value.
<dt>max_val<dd>Pointer to returned maximum value.
<dt>min_loc<dd>Pointer to returned minimum location.
<dt>max_loc<dd>Pointer to returned maximum location.
<dt>mask<dd>The optional mask that is used to select a subarray.
</dl><p>
The function <code>MinMaxLoc</code> finds minimum and maximum element values and their
positions. The extremums are searched over the whole array, selected <code>ROI</code> (in case
of <code>IplImage</code>) or, if <code>mask</code> is not <code>NULL</code>, in the specified array region.
If the array has more than one channel, it must be <code>IplImage</code> with <code>COI</code> set.
In case if multi-dimensional arrays <code>min_loc->x</code> and <code>max_loc->x</code> will contain raw (linear)
positions of the extremums.</p>


<hr><h3><a name="decl_cvNorm">Norm</a></h3>
<p class="Blurb">Calculates absolute array norm, absolute difference norm or relative difference norm</p>
<pre>
double cvNorm( const CvArr* arr1, const CvArr* arr2=NULL, int norm_type=CV_L2, const CvArr* mask=NULL );
</pre><p><dl>
<dt>arr1<dd>The first source image.
<dt>arr2<dd>The second source image. If it is NULL, the absolute norm of <code>arr1</code> is calculated, otherwise
         absolute or relative norm of <code>arr1</code>-<code>arr2</code> is calculated.
<dt>normType<dd>Type of norm, see the discussion.
<dt>mask<dd>The optional operation mask.
</dl><p>
The function <code>cvNorm</code> calculates the absolute norm of <code>arr1</code> if <code>arr2</code> is NULL:</p>
<pre>
norm = ||arr1||<sub>C</sub> = max<sub>I</sub> abs(arr1(I)),  if <code>normType</code> = CV_C

norm = ||arr1||<sub>L1</sub> = sum<sub>I</sub> abs(arr1(I)),  if <code>normType</code> = CV_L1

norm = ||arr1||<sub>L2</sub> = sqrt( sum<sub>I</sub> arr1(I)<sup>2</sup>),  if <code>normType</code> = CV_L2

</pre>
<p>And the function calculates absolute or relative difference norm if <code>arr2</code> is not NULL:</p>
<pre>
norm = ||arr1-arr2||<sub>C</sub> = max<sub>I</sub> abs(arr1(I)-arr2(I)),  if <code>normType</code> = CV_C

norm = ||arr1-arr2||<sub>L1</sub> = sum<sub>I</sub> abs(arr1(I)-arr2(I)),  if <code>normType</code> = CV_L1

norm = ||arr1-arr2||<sub>L2</sub> = sqrt( sum<sub>I</sub> (arr1(I)-arr2(I))<sup>2</sup> ),  if <code>normType</code> = CV_L2

or

norm = ||arr1-arr2||<sub>C</sub>/||arr2||<sub>C</sub>, if <code>normType</code> = CV_RELATIVE_C

norm = ||arr1-arr2||<sub>L1</sub>/||arr2||<sub>L1</sub>, if <code>normType</code> = CV_RELATIVE_L1

norm = ||arr1-arr2||<sub>L2</sub>/||arr2||<sub>L2</sub>, if <code>normType</code> = CV_RELATIVE_L2

</pre>
<p>
The function<code> Norm</code> returns the calculated norm.
The multiple-channel array are treated as single-channel, that is, the results for all channels
are combined.
</p>


<hr><h3><a name="decl_cvReduce">Reduce</a></h3>
<p class="Blurb">Reduces matrix to a vector</p>
<pre>
void cvReduce( const CvArr* src, CvArr* dst, int op=CV_REDUCE_SUM );
</pre><p><dl>
<dt>src<dd>The input matrix.
<dt>dst<dd>The output single-row/single-column vector that accumulates
           somehow all the matrix rows/columns.
<dt>dim<dd>The dimension index along which the matrix is reduce.
           0 means that the matrix is reduced to a single row,
           1 means that the matrix is reduced to a single column.
           -1 means that the dimension is chosen automatically by analysing the <code>dst</code> size.
<dt>op<dd>The reduction operation. It can take of the following values:<br>
           <code>CV_REDUCE_SUM</code> - the output is the sum of all the matrix rows/columns.<br>
           <code>CV_REDUCE_AVG</code> - the output is the mean vector of all the matrix rows/columns.<br>
           <code>CV_REDUCE_MAX</code> - the output is the maximum (column/row-wise) of all the matrix rows/columns.<br>
           <code>CV_REDUCE_MIN</code> - the output is the minimum (column/row-wise) of all the matrix rows/columns.<br>
</dl><p>
The function <code>cvReduce</code> reduces matrix to a vector by treating the matrix rows/columns as a set
of 1D vectors and performing the specified operation on the vectors until a single row/column is obtained.
For example, the function can be used to compute horizontal and vertical projections of an raster image.
In case of <code>CV_REDUCE_SUM</code> and <code>CV_REDUCE_AVG</code> the output may have a larger
element bit-depth to preserve accuracy. And multi-channel arrays are also supported in these two reduction modes.
</p>


<!-- *****************************************************************************************
     *****************************************************************************************
     ***************************************************************************************** -->

<hr><h2><a name="cxcore_arrays_matrix">Linear Algebra</a></h2>

<hr><h3><a name="decl_cvDotProduct">DotProduct</a></h3>
<p class="Blurb">Calculates dot product of two arrays in Euclidian metrics</p>
<pre>
double cvDotProduct( const CvArr* src1, const CvArr* src2 );
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array.
</dl><p>
The function <code>cvDotProduct</code> calculates and returns the Euclidean dot product of two
arrays.</p>
<pre>src1&bull;src2 = sum<sub>I</sub>(src1(I)*src2(I))
</pre>
<p>In case of multiple channel arrays the results for all channels are
accumulated. In particular, <code><a href="#decl_cvDotProduct">cvDotProduct</a>(a,a)</code>,
where <code>a</code> is a complex vector, will return <code>||a||<sup>2</sup></code>.
The function can process multi-dimensional arrays, row by row, layer by layer and so on.</p>


<hr><h3><a name="decl_cvNormalize">Normalize</a></h3>
<p class="Blurb">Normalizes array to a certain norm or value range</p>
<pre>
void cvNormalize( const CvArr* src, CvArr* dst,
                  double a=1, double b=0, int norm_type=CV_L2,
                  const CvArr* mask=NULL );
</pre><p><dl>
<dt>src<dd>The input array.
<dt>dst<dd>The output array; in-place operation is supported.
<dt>a<dd>The minimum/maximum value of the output array or the norm of output array.
<dt>b<dd>The maximum/minimum value of the output array.
<dt>norm_type<dd>The normalization type. It can take one of the following values:<br>
    <code>CV_C</code> - the C-norm (maximum of absolute values) of the array is normalized.<br>
    <code>CV_L1</code> - the L<sub>1</sub>-norm (sum of absolute values) of the array is normalized.<br>
    <code>CV_L2</code> - the (Euclidian) L<sub>2</sub>-norm of the array is normalized.<br>
    <code>CV_MINMAX</code> - the array values are scaled and shifted to the specified range.<br>
<dt>mask<dd>The operation mask. Makes the function consider and normalize only certain array elements.
</dl><p>
The function <code>cvNormalize</code> normalizes the input array so that it's norm or value
range takes the certain value(s).</p>
<p>When <code>norm_type==CV_MINMAX</code>:
<pre>
    dst(i,j)=(src(i,j)-min(src))*(b'-a')/(max(src)-min(src)) + a',  if mask(i,j)!=0
    dst(i,j)=src(i,j)  otherwise
</pre>
where <code>b'=MAX(a,b)</code>, <code>a'=MIN(a,b)</code>;<br>
<code>min(src)</code> and <code>max(src)</code> are the global minimum and maximum, respectively,
of the input array, computed over the whole array or the specified subset of it.
<p>When <code>norm_type!=CV_MINMAX</code>:
<pre>
    dst(i,j)=src(i,j)*a/<a href="#decl_cvNorm">cvNorm</a>(src,0,norm_type,mask), if mask(i,j)!=0
    dst(i,j)=src(i,j)  otherwise
</pre>
<p>Here is the short example:</p>
<pre>
float v[3] = { 1, 2, 3 };
CvMat V = cvMat( 1, 3, CV_32F, v );

// make vector v unit-length;
// equivalent to
//   for(int i=0;i&lt;3;i++) v[i]/=sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
cvNormalize( &V, &V );
</pre>

<hr><h3><a name="decl_cvCrossProduct">CrossProduct</a></h3>
<p class="Blurb">Calculates cross product of two 3D vectors</p>
<pre>
void cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst );
</pre><p><dl>
<dt>src1<dd>The first source vector.
<dt>src2<dd>The second source vector.
<dt>dst<dd>The destination vector.
</dl><p>
The function <code>cvCrossProduct</code> calculates the cross product of two 3D vectors:</p>
<pre>dst = src1 &times; src2, (dst<sub>1</sub> = src1<sub>2</sub>src2<sub>3</sub> - src1<sub>3</sub>src2<sub>2</sub> , dst<sub>2</sub> = src1<sub>3</sub>src2<sub>1</sub> - src1<sub>1</sub>src2<sub>3</sub> , dst<sub>3</sub> = src1<sub>1</sub>src2<sub>2</sub> - src1<sub>2</sub>src2<sub>1</sub>).</pre>


<hr><h3><a name="decl_cvScaleAdd">ScaleAdd</a></h3>
<p class="Blurb">Calculates sum of scaled array and another array</p>
<pre>
void cvScaleAdd( const CvArr* src1, CvScalar scale, const CvArr* src2, CvArr* dst );
#define cvMulAddS cvScaleAdd
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>scale<dd>Scale factor for the first array.
<dt>src2<dd>The second source array.
<dt>dst<dd>The destination array
</dl><p>
The function <code>cvScaleAdd</code> calculates sum of scaled array and another array:</p>
<pre>dst(I)=src1(I)*scale + src2(I)</pre>
<p>All array parameters should have the same type and the same size.</p>


<hr><h3><a name="decl_cvGEMM">GEMM</a></h3>
<p class="Blurb">Performs generalized matrix multiplication</p>
<pre>
void  cvGEMM( const CvArr* src1, const CvArr* src2, double alpha,
              const CvArr* src3, double beta, CvArr* dst, int tABC=0 );
#define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( src1, src2, 1, src3, 1, dst, 0 )
#define cvMatMul( src1, src2, dst ) cvMatMulAdd( src1, src2, 0, dst )
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array.
<dt>src3<dd>The third source array (shift). Can be NULL, if there is no shift.
<dt>dst<dd>The destination array.
<dt>tABC<dd>The operation flags that can be 0 or combination of the following values:<br>
            CV_GEMM_A_T - transpose src1<br>
            CV_GEMM_B_T - transpose src2<br>
            CV_GEMM_C_T - transpose src3<br>
            for example, CV_GEMM_A_T+CV_GEMM_C_T corresponds to
            <pre>alpha*src1<sup>T</sup>*src2 + beta*src<sup>T</sup></pre>
</dl><p>
The function <code>cvGEMM</code> performs generalized matrix multiplication:</p>
<pre>dst = alpha*op(src1)*op(src2) + beta*op(src3), where op(X) is X or X<sup>T</sup></pre>
<p>
All the matrices should have the same data type and the coordinated sizes.
Real or complex floating-point matrices are supported</p>


<hr><h3><a name="decl_cvTransform">Transform</a></h3>
<p class="Blurb">Performs matrix transform of every array element</p>
<pre>
void cvTransform( const CvArr* src, CvArr* dst, const CvMat* transmat, const CvMat* shiftvec=NULL );
</pre><p><dl>
<dt>src<dd>The first source array.
<dt>dst<dd>The destination array.
<dt>transmat<dd>Transformation matrix.
<dt>shiftvec<dd>Optional shift vector.
</dl><p>
The function <code>cvTransform</code> performs matrix transformation of every element of array <code>src</code>
and stores the results in <code>dst</code>:</p>
<pre>dst(I)=transmat*src(I) + shiftvec   or   dst(I)<sub>k</sub>=sum<sub>j</sub>(transmat(k,j)*src(I)<sub>j</sub>) + shiftvec(k)</pre>
<p>That is every element of <code>N</code>-channel array <code>src</code> is considered as <code>N</code>-element vector, which is
transformed using matrix <code>M</code>&times;<code>N</code> matrix <code>transmat</code> and shift vector <code>shiftvec</code>
into an element of <code>M</code>-channel array <code>dst</code>.
There is an option to embedd <code>shiftvec</code> into <code>transmat</code>. In this case <code>transmat</code> should be
<code>M</code>&times;<code>N+1</code> matrix and the right-most column is treated as the shift vector.</p>
<p>
Both source and destination arrays should have the same depth and the same size or selected ROI
size. <code>transmat</code> and <code>shiftvec</code> should be real floating-point matrices.
<p>The function may be used for geometrical transformation of <code>N</code>D point set,
arbitrary linear color space transformation, shuffling the channels etc.
</p>

<hr><h3><a name="decl_cvPerspectiveTransform">PerspectiveTransform</a></h3>
<p class="Blurb">Performs perspective matrix transform of vector array</p>
<pre>
void cvPerspectiveTransform( const CvArr* src, CvArr* dst, const CvMat* mat );
</pre><p><dl>
<dt>src<dd>The source three-channel floating-point array.
<dt>dst<dd>The destination three-channel floating-point array.
<dt>mat<dd>3&times;3 or 4&times;4 transformation matrix.
</dl><p>
The function <code>cvPerspectiveTransform</code> transforms every element of <code>src</code>
(by treating it as 2D or 3D vector) in the following way:</p>
<pre>
(x, y, z) -> (x&#146;/w, y&#146;/w, z&#146;/w) or
(x, y) -> (x&#146;/w, y&#146;/w),

where
(x&#146;, y&#146;, z&#146;, w&#146;) = mat4x4*(x, y, z, 1) or
(x&#146;, y&#146;, w&#146;) = mat3x3*(x, y, 1)

and w = w&#146;   if w&#146;!=0,
        inf  otherwise
</pre>


<hr><h3><a name="decl_cvMulTransposed">MulTransposed</a></h3>
<p class="Blurb">Calculates product of array and transposed array</p>
<pre>
void cvMulTransposed( const CvArr* src, CvArr* dst, int order, const CvArr* delta=NULL );
</pre><p><dl>
<dt>src<dd>The source matrix.
<dt>dst<dd>The destination matrix.
<dt>order<dd>Order of multipliers.
<dt>delta<dd>An optional array, subtracted from <code>src</code> before multiplication.
</dl><p>
The function <code>cvMulTransposed</code> calculates the product of src and its transposition.</p>
<p>The function evaluates</p>
<pre>dst=(src-delta)*(src-delta)<sup>T</sup></pre>
<p>if order=0, and
<pre>dst=(src-delta)<sup>T</sup>*(src-delta)</pre>
<p>otherwise.</p>


<hr><h3><a name="decl_cvTrace">Trace</a></h3>
<p class="Blurb">Returns trace of matrix</p>
<pre>
CvScalar cvTrace( const CvArr* mat );
</pre><p><dl>
<dt>mat<dd>The source matrix.
</dl><p>
The function <code>cvTrace</code> returns sum of diagonal elements of the matrix <code>src1</code>.
<pre>
tr(src1)=sum<sub>i</sub>mat(i,i)
</pre>


<hr><h3><a name="decl_cvTranspose">Transpose</a></h3>
<p class="Blurb">Transposes matrix</p>
<pre>
void cvTranspose( const CvArr* src, CvArr* dst );
#define cvT cvTranspose
</pre><p><dl>
<dt>src<dd>The source matrix.
<dt>dst<dd>The destination matrix.
</dl><p>
The function <code>cvTranspose</code> transposes matrix <code>src1</code>:</p>
<pre>
dst(i,j)=src(j,i)
</pre>
<p>Note that no complex conjugation is done in case of complex matrix. Conjugation
should be done separately: look at the sample code in <a href="#decl_cvXorS">cvXorS</a> for example</p>


<hr><h3><a name="decl_cvDet">Det</a></h3>
<p class="Blurb">Returns determinant of matrix</p>
<pre>
double cvDet( const CvArr* mat );
</pre><p><dl>
<dt>mat<dd>The source matrix.
</dl><p>
The function <code>cvDet</code> returns determinant of the square matrix <code>mat</code>.
The direct method is used for small matrices and Gaussian elimination is used for larger matrices.
For symmetric positive-determined matrices it is also possible to run <a href="#decl_cvSVD">SVD</a>
with <code>U=V=NULL</code> and then calculate determinant as a product of the diagonal elements of <code>W</code></p>


<hr><h3><a name="decl_cvInvert">Invert</a></h3>
<p class="Blurb">Finds inverse or pseudo-inverse of matrix</p>
<pre>
double cvInvert( const CvArr* src, CvArr* dst, int method=CV_LU );
#define cvInv cvInvert
</pre><p><dl>
<dt>src<dd>The source matrix.
<dt>dst<dd>The destination matrix.
<dt>method<dd>Inversion method:<br>
              CV_LU - Gaussian elimination with optimal pivot element chose<br>
              CV_SVD - Singular value decomposition (SVD) method<br>
              CV_SVD_SYM - SVD method for a symmetric positively-defined matrix<br>
</dl><p>
The function <code>cvInvert</code> inverts matrix <code>src1</code> and stores the result in <code>src2</code></p>
<p>In case of <code>LU</code> method the function returns <code>src1</code> determinant (src1 must be square).
If it is 0, the matrix is not inverted and <code>src2</code> is filled with zeros.</p>
<p>In case of <code>SVD</code> methods the function returns the inversed condition number of <code>src1</code>
(ratio of the smallest singular value to the largest singular value) and 0 if <code>src1</code> is all zeros.
The SVD methods calculate a pseudo-inverse matrix if <code>src1</code> is singular</p>


<hr><h3><a name="decl_cvSolve">Solve</a></h3>
<p class="Blurb">Solves linear system or least-squares problem</p>
<pre>
int cvSolve( const CvArr* A, const CvArr* B, CvArr* X, int method=CV_LU );
</pre><p><dl>
<dt>A<dd>The source matrix.
<dt>B<dd>The right-hand part of the linear system.
<dt>X<dd>The output solution.
<dt>method<dd>The solution (matrix inversion) method:<br>
              CV_LU - Gaussian elimination with optimal pivot element chose<br>
              CV_SVD - Singular value decomposition (SVD) method<br>
              CV_SVD_SYM - SVD method for a symmetric positively-defined matrix.
</dl><p>
The function <code>cvSolve</code> solves linear system or least-squares problem (the latter
is possible with SVD methods):</p>
<pre>
dst = arg min<sub>X</sub>||A*X-B||
</pre>
<p>If <code>CV_LU</code> method is used, the function returns 1 if <code>src1</code> is non-singular and
0 otherwise, in the latter case <code>dst</code> is not valid</p>


<hr><h3><a name="decl_cvSVD">SVD</a></h3>
<p class="Blurb">Performs singular value decomposition of real floating-point matrix</p>
<pre>
void cvSVD( CvArr* A, CvArr* W, CvArr* U=NULL, CvArr* V=NULL, int flags=0 );
</pre><p><dl>

<dt>A<dd>Source <code>M</code>&times;<code>N</code> matrix.
<dt>W<dd>Resulting singular value matrix (<code>M</code>&times;<code>N</code> or <code>N</code>&times;<code>N</code>) or
         vector (<code>N</code>&times;<code>1</code>).
<dt>U<dd>Optional left orthogonal matrix (<code>M</code>&times;<code>M</code> or <code>M</code>&times;<code>N</code>).
         If CV_SVD_U_T is specified, the number of rows and columns in the sentence above should be swapped.
<dt>V<dd>Optional right orthogonal matrix (<code>N</code>&times;<code>N</code>)
<dt>flags<dd>Operation flags; can be 0 or combination of the following values:
<ul>
<li>  <code>CV_SVD_MODIFY_A</code> enables modification of matrix <code>src1</code> during the operation. It
  speeds up the processing.
<li>  <code>CV_SVD_U_T</code> means that the tranposed matrix <code>U</code> is returned.
      Specifying the flag speeds up the processing.
<li>  <code>CV_SVD_V_T</code> means that the tranposed matrix <code>V</code> is returned.
      Specifying the flag speeds up the processing.
</ul>
</dl><p>
The function <code>cvSVD</code> decomposes matrix <code>A</code> into a product of a diagonal matrix and two
orthogonal matrices:</p>
<pre>
A=U*W*V<sup>T</sup>
</pre>
<p>Where <code>W</code> is diagonal matrix of singular values that can be coded as a 1D
vector of singular values and <code>U</code> and <code>V</code>. All the singular values are non-negative and sorted (together with <code>U</code> and
and <code>V</code> columns) in descenting order.</p>
<p>SVD algorithm is numerically robust and its typical applications include:
<ul>
<li>accurate eigenvalue problem solution when matrix <code>A</code> is square, symmetric and positively
  defined matrix, for example, when it is a covariation matrix.
  <code>W</code> in this case will be a vector of eigen values, and <code>U</code>=<code>V</code> is matrix of
  eigen vectors (thus, only one of <code>U</code> or <code>V</code> needs to be calculated if
  the eigen vectors are required)</li>
<li>accurate solution of poor-conditioned linear systems</li>
<li>least-squares solution of overdetermined linear systems. This and previous is done by <a href="#decl_cvSolve">cvSolve</a>
    function with <code>CV_SVD</code> method</li>
<li>accurate calculation of different matrix characteristics such as rank
   (number of non-zero singular values),
  condition number (ratio of the largest singular value to the smallest one),
  determinant (absolute value of determinant is equal to the product of singular values).
  All the things listed in this item do not require calculation of <code>U</code>
  and <code>V</code> matrices.</li>
</ul></p>



<hr><h3><a name="decl_cvSVBkSb">SVBkSb</a></h3>
<p class="Blurb">Performs singular value back substitution</p>
<pre>
void  cvSVBkSb( const CvArr* W, const CvArr* U, const CvArr* V,
                const CvArr* B, CvArr* X, int flags );
</pre><p><dl>

<dt>W<dd>Matrix or vector of singular values.
<dt>U<dd>Left orthogonal matrix (tranposed, perhaps)
<dt>V<dd>Right orthogonal matrix (tranposed, perhaps)
<dt>B<dd>The matrix to multiply the pseudo-inverse of the original matrix <code>A</code> by.
         This is the optional parameter. If it is omitted then it is assumed to be
         an identity matrix of an appropriate size (So <code>X</code> will be the reconstructed
         pseudo-inverse of <code>A</code>).
<dt>X<dd>The destination matrix: result of back substitution.
<dt>flags<dd>Operation flags, should match exactly to the <code>flags</code> passed to <a href="#decl_cvSVD">cvSVD</a>.
</dl><p>
The function <code>cvSVBkSb</code> calculates back substitution for decomposed matrix <code>A</code> (see
<a href="#decl_cvSVD">cvSVD</a> description) and matrix <code>B</code>:</p>
<pre>
X=V*W<sup>-1</sup>*U<sup>T</sup>*B
</pre>
<p>Where</p>
<pre>
W<sup>-1</sup>(i,i)=1/W(i,i) if W(i,i) > epsilon&bull;sum<sub>i</sub>W(i,i),
                    0        otherwise
</pre>
<p>And <code>epsilon</code> is a small number that depends on the matrix data type.
</p>
This function together with <a href="#decl_cvSVD">cvSVD</a> is used inside <a href="#decl_cvInvert">cvInvert</a> and <a href="#decl_cvSolve">cvSolve</a>,
and the possible reason to use these (svd &amp; bksb) "low-level" function is to avoid
temporary matrices allocation inside the high-level counterparts (inv &amp; solve).</p>


<hr><h3><a name="decl_cvEigenVV">EigenVV</a></h3>
<p class="Blurb">Computes eigenvalues and eigenvectors of symmetric matrix</p>
<pre>
void cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, double eps=0 );
</pre><p><dl>
<dt>mat<dd>The input symmetric square matrix. It is modified during the processing.
<dt>evects<dd>The output matrix of eigenvectors, stored as a subsequent rows.
<dt>evals<dd>The output vector of eigenvalues, stored in the descenting order (order of
eigenvalues and eigenvectors is syncronized, of course).
<dt>eps<dd>Accuracy of diagonalization (typically, DBL_EPSILON=&asymp;10<sup>-15</sup> is enough).
</dl><p>
The function <code>cvEigenVV</code> computes the eigenvalues and eigenvectors of the matrix <code>A</code>:</p>
<pre>mat*evects(i,:)' = evals(i)*evects(i,:)' (in MATLAB notation)</pre>
<p>The contents of matrix <code>A</code> is destroyed by the function.</p>
<p>Currently the function is slower than <a href="#decl_cvSVD">cvSVD</a> yet less accurate,
so if <code>A</code> is known to be positively-defined (for example, it is a covariation matrix),
it is recommended to use <a href="#decl_cvSVD">cvSVD</a> to find eigenvalues and eigenvectors of <code>A</code>,
especially if eigenvectors are not required. That is, instead of
<pre>
cvEigenVV(mat, eigenvals, eigenvects);
</pre>
call
<pre>
cvSVD(mat, eigenvals, eigenvects, 0, CV_SVD_U_T + CV_SVD_MODIFY_A);
</pre>
</p>


<hr><h3><a name="decl_cvCalcCovarMatrix">CalcCovarMatrix</a></h3>
<p class="Blurb">Calculates covariation matrix of the set of vectors</p>
<pre>
void cvCalcCovarMatrix( const CvArr** vects, int count, CvArr* cov_mat, CvArr* avg, int flags );
</pre><p><dl>
<dt>vects<dd>The input vectors. They all must have the same type and the same size.
             The vectors do not have to be 1D, they can be 2D (e.g. images) etc.
<dt>count<dd>The number of input vectors.
<dt>cov_mat<dd>The output covariation matrix that should be floating-point and square.
<dt>avg<dd>The input or output (depending on the flags) array - the mean (average) vector of the input vectors.
<dt>flags<dd>The operation flags, a combination of the following values:<br>
                 <code>CV_COVAR_SCRAMBLED</code> - the output covaration matrix is calculated as:<br>
                       <code>scale*[vects[0]-avg,vects[1]-avg,...]<sup>T</sup>*[vects[0]-avg,vects[1]-avg,...]</code>,<br>
                       that is, the covariation matrix is <code>count</code>&times;<code>count</code>. Such an unusual
                       covariation matrix is used for fast PCA of a set of very large vectors
                       (see, for example, EigenFaces technique for face recognition). Eigenvalues of this
                       "scrambled" matrix will match to the eigenvalues of the true covariation matrix and
                       the "true" eigenvectors can be easily calculated from the eigenvectors of the "scrambled" covariation
                       matrix.<br>
                 <code>CV_COVAR_NORMAL</code> - the output covaration matrix is calculated as:<br>
                       <code>scale*[vects[0]-avg,vects[1]-avg,...]*[vects[0]-avg,vects[1]-avg,...]<sup>T</sup></code>,<br>
                       that is, <code>cov_mat</code> will be a usual covariation matrix with the same linear size as the total number of
                       elements in every input vector. One and only one of <code>CV_COVAR_SCRAMBLED</code> and <code>CV_COVAR_NORMAL</code> must be specified<br>
                 <code>CV_COVAR_USE_AVG</code> - if the flag is specified, the function does not calculate <code>avg</code> from
                       the input vectors, but, instead, uses the passed <code>avg</code> vector. This is useful if <code>avg</code>
                       has been already calculated somehow, or if the covariation matrix is calculated by parts - in this case,
                       <code>avg</code> is not a mean vector of the input sub-set of vectors, but rather the mean vector of
                       the whole set.<br>
                 <code>CV_COVAR_SCALE</code> - if the flag is specified, the covariation matrix is scaled by
                       the number of input vectors.
                 <code>CV_COVAR_ROWS</code> - Means that all the input vectors are stored as rows of a single matrix, <code>vects[0]</code>.
                       <code>count</code> is ignored in this case, and <code>avg</code> should be a single-row vector of an appropriate size.
                 <code>CV_COVAR_COLS</code> - Means that all the input vectors are stored as columns of a single matrix, <code>vects[0]</code>.
                       <code>count</code> is ignored in this case, and <code>avg</code> should be a single-column vector of an appropriate size.
</dl><p>
The function <code>cvCalcCovarMatrix</code> calculates the covariation matrix and, optionally,
mean vector of the set of input vectors. The function can be used for PCA, for comparing vectors using Mahalanobis distance etc.
</p>


<hr><h3><a name="decl_cvMahalonobis">Mahalonobis</a></h3>
<p class="Blurb">Calculates Mahalonobis distance between two vectors</p>
<pre>
double cvMahalanobis( const CvArr* vec1, const CvArr* vec2, CvArr* mat );
</pre><p><dl>
<dt>vec1<dd>The first 1D source vector.
<dt>vec2<dd>The second 1D source vector.
<dt>mat<dd>The inverse covariation matrix.
</dl><p>
The function <code>cvMahalonobis</code> calculates the weighted distance between two vectors
and returns it:</p>
<pre>
d(vec1,vec2)=sqrt( sum<sub>i,j</sub> {mat(i,j)*(vec1(i)-vec2(i))*(vec1(j)-vec2(j))} )
</pre>
<p>The covariation matrix may be calculated using <a href="#decl_cvCalcCovarMatrix">cvCalcCovarMatrix</a> function and further
inverted using <a href="#decl_cvInvert">cvInvert</a> function (CV_SVD method is the preffered one, because the matrix
might be singular).</p>


<hr><h3><a name="decl_cvCalcPCA">CalcPCA</a></h3>
<p class="Blurb">Performs Principal Component Analysis of a vector set</p>
<pre>
void cvCalcPCA( const CvArr* data, CvArr* avg,
                CvArr* eigenvalues, CvArr* eigenvectors, int flags );
</pre><p><dl>
<dt>data<dd>The input data; each vector is either a single row (<code>CV_PCA_DATA_AS_ROW</code>)
            or a single column (<code>CV_PCA_DATA_AS_COL</code>).
<dt>avg<dd>The mean (average) vector, computed inside the function or provided by user.
<dt>eigenvalues<dd>The output eigenvalues of covariation matrix.
<dt>eigenvectors<dd>The output eigenvectors of covariation matrix (i.e. principal components);
                    one vector per row.
<dt>flags<dd>The operation flags, a combination of the following values:<br>
             <code>CV_PCA_DATA_AS_ROW</code> - the vectors are stored as rows
             (i.e. all the components of a certain vector are stored continously)<br>
             <code>CV_PCA_DATA_AS_COL</code> - the vectors are stored as columns
             (i.e. values of a certain vector component are stored continuously)<br>
             (the above two flags are mutually exclusive)<br>
             <code>CV_PCA_USE_AVG</code> - use pre-computed average vector<br>
</dl><p>
The function <code>cvCalcPCA</code> performs PCA analysis of the vector set.
First, it uses <a href="#decl_cvCalcCovarMatrix">cvCalcCovarMatrix</a> to compute covariation matrix
and then it finds its eigenvalues and eigenvectors. The output number of eigenvalues/eigenvectors
should be less than or equal to <code>MIN(rows(data),cols(data))</code>.


<hr><h3><a name="decl_cvProjectPCA">ProjectPCA</a></h3>
<p class="Blurb">Projects vectors to the specified subspace</p>
<pre>
void cvProjectPCA( const CvArr* data, const CvArr* avg,
                   const CvArr* eigenvectors, CvArr* result )
</pre><p><dl>
<dt>data<dd>The input data; each vector is either a single row
            or a single column.
<dt>avg<dd>The mean (average) vector. If it is a single-row vector,
           it means that the input vectors are stored as rows of <code>data</code>;
           otherwise, it should be a single-column vector,
           then the vectors are stored as columns of <code>data</code>.
<dt>eigenvectors<dd>The eigenvectors (principal components); one vector per row.
<dt>result<dd>The output matrix of decomposition coefficients. The number of rows must be
              the same as the number of vectors, the number of columns must
              be less than or equal to the number of rows in <code>eigenvectors</code>.
              That it is less, the input vectors are projected into subspace
              of the first <code>cols(result)</code> principal components.
</dl><p>
The function <code>cvProjectPCA</code> projects input vectors to the subspace represented by the
orthonormal basis (<code>eigenvectors</code>). Before computing the dot products, <code>avg</code>
vector is subtracted from the input vectors:</p>
<pre>
result(i,:)=(data(i,:)-avg)*eigenvectors' // for CV_PCA_DATA_AS_ROW layout.
</pre>


<hr><h3><a name="decl_cvBackProjectPCA">BackProjectPCA</a></h3>
<p class="Blurb">Reconstructs the original vectors from the projection coefficients</p>
<pre>
void cvBackProjectPCA( const CvArr* proj, const CvArr* avg,
                       const CvArr* eigenvects, CvArr* result );
</pre><p><dl>
<dt>proj<dd>The input data; in the same format as <code>result</code> in
            <a href="#decl_cvProjectPCA">cvProjectPCA</a>.
<dt>avg<dd>The mean (average) vector. If it is a single-row vector,
           it means that the output vectors are stored as rows of <code>result</code>;
           otherwise, it should be a single-column vector,
           then the vectors are stored as columns of <code>result</code>.
<dt>eigenvectors<dd>The eigenvectors (principal components); one vector per row.
<dt>result<dd>The output matrix of reconstructed vectors.
</dl><p>
The function <code>cvBackProjectPCA</code> reconstructs the vectors from the projection coefficients:</p>
<pre>
result(i,:)=proj(i,:)*eigenvectors + avg // for CV_PCA_DATA_AS_ROW layout.
</pre>


<hr><h2><a name="cxcore_arrays_math">Math Functions</a></h2>

<hr><h3><a name="decl_cvRound">Round, Floor, Ceil</a></h3>
<p class="Blurb">Converts floating-point number to integer</p>
<pre>
int cvRound( double value );
int cvFloor( double value );
int cvCeil( double value );
</pre><p><dl>
<dt>value<dd>The input floating-point value
</dl><p>
The functions <code>cvRound, cvFloor</code> and <code>cvCeil</code> convert input floating-point number to
integer using one of the rounding modes. <code>cvRound</code> returns the nearest integer value to
the argument.
<code>cvFloor</code> returns the maximum integer value that is not larger than the argument.
<code>cvCeil</code> returns the minimum integer value that is not smaller than the argument.
On some architectures the functions work <em>much</em> faster than the standard cast operations in C.
If absolute value of the argument is greater than 2<sup>31</sup>, the result is not determined.
Special values (&plusmn;Inf, NaN) are not handled.
</p>


<hr><h3><a name="decl_cvSqrt">Sqrt</a></h3>
<p class="Blurb">Calculates square root</p>
<pre>
float cvSqrt( float value );
</pre><p><dl>
<dt>value<dd>The input floating-point value
</dl><p>
The function <code>cvSqrt</code> calculates square root of the argument.
If the argument is negative, the result is not determined.
</p>


<hr><h3><a name="decl_cvInvSqrt">InvSqrt</a></h3>
<p class="Blurb">Calculates inverse square root</p>
<pre>
float cvInvSqrt( float value );
</pre><p><dl>
<dt>value<dd>The input floating-point value
</dl><p>
The function <code>cvInvSqrt</code> calculates inverse square root of the argument, and
normally it is faster than <code>1./sqrt(value)</code>. If the argument is zero or negative, the result is
not determined. Special values (&plusmn;Inf, NaN) are not handled.
</p>


<hr><h3><a name="decl_cvCbrt">Cbrt</a></h3>
<p class="Blurb">Calculates cubic root</p>
<pre>
float cvCbrt( float value );
</pre><p><dl>
<dt>value<dd>The input floating-point value
</dl><p>
The function <code>cvCbrt</code> calculates cubic root of the argument, and
normally it is faster than <code>pow(value,1./3)</code>. Besides, negative arguments are handled properly.
Special values (&plusmn;Inf, NaN) are not handled.
</p>


<hr><h3><a name="decl_cvFastArctan">FastArctan</a></h3>
<p class="Blurb">Calculates angle of 2D vector</p>
<pre>
float cvFastArctan( float y, float x );
</pre><p><dl>
<dt>x<dd>x-coordinate of 2D vector
<dt>y<dd>y-coordinate of 2D vector
</dl><p>
The function <code>cvFastArctan</code> calculates full-range angle of input 2D vector.
The angle is measured in degrees and varies from 0&deg; to 360&deg;. The accuracy is ~0.1&deg;
</p>


<hr><h3><a name="decl_cvIsNaN">IsNaN</a></h3>
<p class="Blurb">Determines if the argument is Not A Number</p>
<pre>
int cvIsNaN( double value );
</pre><p><dl>
<dt>value<dd>The input floating-point value
</dl><p>
The function <code>cvIsNaN</code> returns 1 if the argument is Not A Number (as defined
by IEEE754 standard), 0 otherwise.
</p>

<hr><h3><a name="decl_cvIsInf">IsInf</a></h3>
<p class="Blurb">Determines if the argument is Infinity</p>
<pre>
int cvIsInf( double value );
</pre><p><dl>
<dt>value<dd>The input floating-point value
</dl><p>
The function <code>cvIsInf</code> returns 1 if the argument is &plusmn;Infinity (as defined
by IEEE754 standard), 0 otherwise.
</p>


<hr><h3><a name="decl_cvCartToPolar">CartToPolar</a></h3>
<p class="Blurb">Calculates magnitude and/or angle of 2d vectors</p>
<pre>
void cvCartToPolar( const CvArr* x, const CvArr* y, CvArr* magnitude,
                    CvArr* angle=NULL, int angle_in_degrees=0 );
</pre><p><dl>
<dt>x<dd>The array of x-coordinates
<dt>y<dd>The array of y-coordinates
<dt>magnitude<dd>The destination array of magnitudes, may be set to NULL if it is not needed
<dt>angle<dd>The destination array of angles, may be set to NULL if it is not needed.
        The angles are measured in radians (0..2&pi;) or in degrees (0..360&deg;).
<dt>angle_in_degrees<dd>The flag indicating whether the angles are measured in radians,
                        which is default mode, or in degrees.
</dl><p>
The function <code>cvCartToPolar</code> calculates either magnitude, angle,
or both of every 2d vector <code>(x(I),y(I))</code>:</p>
<pre>
magnitude(I)=sqrt( x(I)<sup>2</sup>+y(I)<sup>2</sup> ),
angle(I)=atan( y(I)/x(I) )
</pre>
<p>The angles are calculated with &asymp;0.1&deg; accuracy. For (0,0) point the angle
is set to 0.</p>


<hr><h3><a name="decl_cvPolarToCart">PolarToCart</a></h3>
<p class="Blurb">Calculates cartesian coordinates of 2d vectors represented in polar form</p>
<pre>
void cvPolarToCart( const CvArr* magnitude, const CvArr* angle,
                    CvArr* x, CvArr* y, int angle_in_degrees=0 );
</pre><p><dl>
<dt>magnitude<dd>The array of magnitudes. If it is NULL, the magnitudes are assumed all 1&#146;s.
<dt>angle<dd>The array of angles, whether in radians or degrees.
<dt>x<dd>The destination array of x-coordinates, may be set to NULL if it is not needed.
<dt>y<dd>The destination array of y-coordinates, mau be set to NULL if it is not needed.
<dt>angle_in_degrees<dd>The flag indicating whether the angles are measured in radians,
                        which is default mode, or in degrees.
</dl><p>
The function <code>cvPolarToCart</code> calculates either x-coodinate, y-coordinate
or both of every vector <code>magnitude(I)*exp(angle(I)*j), j=sqrt(-1)</code>:</p>
<pre>
x(I)=magnitude(I)*cos(angle(I)),
y(I)=magnitude(I)*sin(angle(I))
</pre>


<hr><h3><a name="decl_cvPow">Pow</a></h3>
<p class="Blurb">Raises every array element to power</p>
<pre>
void cvPow( const CvArr* src, CvArr* dst, double power );
</pre><p><dl>
<dt>src<dd>The source array.
<dt>dst<dd>The destination array, should be the same type as the source.
<dt>power<dd>The exponent of power.
</dl><p>
The function <code>cvPow</code> raises every element of input array to <code>p</code>:</p>
<pre>
dst(I)=src(I)<sup>p</sup>, if <code>p</code> is integer
dst(I)=abs(src(I))<sup>p</sup>, otherwise
</pre>
<p>That is, for non-integer power exponent the absolute values of input
array elements are used. However, it is possible to get true values
for negative values using some extra operations, as the following sample,
computing cube root of array elements, shows:</p>
<pre>
CvSize size = cvGetSize(src);
CvMat* mask = cvCreateMat( size.height, size.width, CV_8UC1 );
cvCmpS( src, 0, mask, CV_CMP_LT ); /* find negative elements */
cvPow( src, dst, 1./3 );
cvSubRS( dst, cvScalarAll(0), dst, mask ); /* negate the results of negative inputs */
cvReleaseMat( &mask );
</pre>
<p>For some values of <code>power</code>, such as integer values, 0.5 and -0.5,
specialized faster algorithms are used.</p>


<hr><h3><a name="decl_cvExp">Exp</a></h3>
<p class="Blurb">Calculates exponent of every array element</p>
<pre>
void cvExp( const CvArr* src, CvArr* dst );
</pre><p><dl>
<dt>src<dd>The source array.
<dt>dst<dd>The destination array, it should have <code>double</code> type or
the same type as the source.
</dl><p>
The function <code>cvExp</code> calculates exponent of every element of input array:</p>
<pre>
dst(I)=exp(src(I))
</pre>
<p>Maximum relative error is &asymp;7e-6. Currently,
the function converts denormalized values to zeros on output.</p>


<hr><h3><a name="decl_cvLog">Log</a></h3>
<p class="Blurb">Calculates natural logarithm of every array element absolute value</p>
<pre>
void cvLog( const CvArr* src, CvArr* dst );
</pre><p><dl>
<dt>src<dd>The source array.
<dt>dst<dd>The destination array, it should have <code>double</code> type or
the same type as the source.
</dl><p>
The function <code>cvLog</code> calculates natural logarithm
of absolute value of every element of input array:</p>
<pre>
dst(I)=log(abs(src(I))), src(I)!=0
dst(I)=C,  src(I)=0
</pre>
Where <code>C</code> is large negative number (&asymp;-700 in the current implementation)</p>


<hr><h3><a name="decl_cvSolveCubic">SolveCubic</a></h3>
<p class="Blurb">Finds real roots of a cubic equation</p>
<pre>
int cvSolveCubic( const CvMat* coeffs, CvMat* roots );
</pre><p><dl>
<dt>coeffs<dd>The equation coefficients, array of 3 or 4 elements.
<dt>roots<dd>The output array of real roots. Should have 3 elements.
</dl><p>
The function <code>cvSolveCubic</code> finds real roots of a cubic equation:</p>
<pre>
coeffs[0]*x<sup>3</sup> + coeffs[1]*x<sup>2</sup> + coeffs[2]*x + coeffs[3] = 0
(if coeffs is 4-element vector)

or

x<sup>3</sup> + coeffs[0]*x<sup>2</sup> + coeffs[1]*x + coeffs[2] = 0
(if coeffs is 3-element vector)
</pre>

<p>The function returns the number of real roots found. The roots are stored
to <code>root</code> array, which is padded with zeros if there is only one root.</p>

<hr><h2><a name="cxcore_arrays_rng">Random Number Generation</a></h2>

<hr><h3><a name="decl_cvRNG">RNG</a></h3>
<p class="Blurb">Initializes random number generator state</p>
<pre>
CvRNG cvRNG( int64 seed=-1 );
</pre><p><dl>
<dt>seed<dd>64-bit value used to initiate a random sequence.
</dl><p>
The function <code>cvRNG</code> initializes random number generator
and returns the state. Pointer to the state can be then passed to <a href="#decl_cvRandInt">cvRandInt</a>,
<a href="#decl_cvRandReal">cvRandReal</a> and <a href="#decl_cvRandArr">cvRandArr</a> functions.
In the current implementation a multiply-with-carry generator is used.</p>


<hr><h3><a name="decl_cvRandArr">RandArr</a></h3>
<p class="Blurb">Fills array with random numbers and updates the RNG state</p>
<pre>
void cvRandArr( CvRNG* rng, CvArr* arr, int dist_type, CvScalar param1, CvScalar param2 );
</pre><p><dl>
<dt>rng<dd>RNG state initialized by <a href="#decl_cvRNG">cvRNG</a>.
<dt>arr<dd>The destination array.
<dt>dist_type<dd>Distribution type:<br>
                     CV_RAND_UNI - uniform distribution<br>
                     CV_RAND_NORMAL - normal or Gaussian distribution<br>
<dt>param1<dd>The first parameter of distribution. In case of uniform distribution it is
              the inclusive lower boundary of random numbers range. In case of
              normal distribution it is the mean value of random numbers.
<dt>param2<dd>The second parameter of distribution. In case of uniform distribution it is
              the exclusive upper boundary of random numbers range. In case of
              normal distribution it is the standard deviation of random numbers.
</dl><p>
The function <code>cvRandArr</code> fills the destination array with
uniformly or normally distributed random numbers. In the sample below
the function is used to add a few normally distributed
floating-point numbers to random locations within a 2d array</p>
<pre>
/* let noisy_screen be the floating-point 2d array that is to be "crapped" */
CvRNG rng_state = cvRNG(0xffffffff);
int i, pointCount = 1000;
/* allocate the array of coordinates of points */
CvMat* locations = cvCreateMat( pointCount, 1, CV_32SC2 );
/* arr of random point values */
CvMat* values = cvCreateMat( pointCount, 1, CV_32FC1 );
CvSize size = cvGetSize( noisy_screen );

cvRandInit( &rng_state,
            0, 1, /* use dummy parameters now and adjust them further */
            0xffffffff /* just use a fixed seed here */,
            CV_RAND_UNI /* specify uniform type */ );

/* initialize the locations */
cvRandArr( &rng_state, locations, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(size.width,size.height,0,0) );

/* modify RNG to make it produce normally distributed values */
rng_state.disttype = CV_RAND_NORMAL;
cvRandSetRange( &rng_state,
                30 /* deviation */,
                100 /* average point brightness */,
                -1 /* initialize all the dimensions */ );
/* generate values */
cvRandArr( &rng_state, values, CV_RAND_NORMAL,
           cvRealScalar(100), // average intensity
           cvRealScalar(30) // deviation of the intensity
           );

/* set the points */
for( i = 0; i &lt; pointCount; i++ )
{
    CvPoint pt = *(CvPoint*)cvPtr1D( locations, i, 0 );
    float value = *(float*)cvPtr1D( values, i, 0 );
    *((float*)cvPtr2D( noisy_screen, pt.y, pt.x, 0 )) += value;
}

/* not to forget to release the temporary arrays */
cvReleaseMat( &locations );
cvReleaseMat( &values );

/* RNG state does not need to be deallocated */
</pre>


<hr><h3><a name="decl_cvRandInt">RandInt</a></h3>
<p class="Blurb">Returns 32-bit unsigned integer and updates RNG</p>
<pre>
unsigned cvRandInt( CvRNG* rng );
</pre><p><dl>
<dt>rng<dd>RNG state initialized by <code>RandInit</code> and, optionally,
customized by <code>RandSetRange</code> (though, the latter function does not
affect on the discussed function outcome).
</dl><p>
The function <code>cvRandInt</code> returns uniformly-distributed random
32-bit unsigned integer and updates RNG state. It is similar to rand() function from C runtime library,
but it always generates 32-bit number whereas rand() returns a number in between 0
and <code>RAND_MAX</code> which is 2**16 or 2**32, depending on the platform.</p><p>
The function is useful for generating scalar random numbers, such as points, patch sizes,
table indices etc, where integer numbers of a certain range can be generated using
modulo operation and floating-point numbers can be generated by scaling to
0..1 of any other specific range. Here is the example from the previous function discussion
rewritten using <a href="#decl_cvRandInt">cvRandInt</a>:</p>
<pre>
/* the input and the task is the same as in the previous sample. */
CvRNG rng_state = cvRNG(0xffffffff);
int i, pointCount = 1000;
/* ... - no arrays are allocated here */
CvSize size = cvGetSize( noisy_screen );
/* make a buffer for normally distributed numbers to reduce call overhead */
#define bufferSize 16
float normalValueBuffer[bufferSize];
CvMat normalValueMat = cvMat( bufferSize, 1, CV_32F, normalValueBuffer );
int valuesLeft = 0;

for( i = 0; i &lt; pointCount; i++ )
{
    CvPoint pt;
    /* generate random point */
    pt.x = cvRandInt( &rng_state ) % size.width;
    pt.y = cvRandInt( &rng_state ) % size.height;

    if( valuesLeft &lt;= 0 )
    {
        /* fulfill the buffer with normally distributed numbers if the buffer is empty */
        cvRandArr( &rng_state, &normalValueMat, CV_RAND_NORMAL, cvRealScalar(100), cvRealScalar(30) );
        valuesLeft = bufferSize;
    }
    *((float*)cvPtr2D( noisy_screen, pt.y, pt.x, 0 ) = normalValueBuffer[--valuesLeft];
}

/* there is no need to deallocate normalValueMat because we have
both the matrix header and the data on stack. It is a common and efficient
practice of working with small, fixed-size matrices */
</pre>


<hr><h3><a name="decl_cvRandReal">RandReal</a></h3>
<p class="Blurb">Returns floating-point random number and updates RNG</p>
<pre>
double cvRandReal( CvRNG* rng );
</pre><p><dl>
<dt>rng<dd>RNG state initialized by <a href="#decl_cvRNG">cvRNG</a>.
</dl><p>
The function <code>cvRandReal</code> returns uniformly-distributed random
floating-point number from 0..1 range (1 is not included).</p>


<hr><h2><a name="cxcore_arrays_dxt">Discrete Transforms</a></h2>

<hr><h3><a name="decl_cvDFT">DFT</a></h3>
<p class="Blurb">Performs forward or inverse Discrete Fourier transform of 1D or 2D floating-point array</p>
<pre>
#define CV_DXT_FORWARD  0
#define CV_DXT_INVERSE  1
#define CV_DXT_SCALE    2
#define CV_DXT_ROWS     4
#define CV_DXT_INV_SCALE (CV_DXT_SCALE|CV_DXT_INVERSE)
#define CV_DXT_INVERSE_SCALE CV_DXT_INV_SCALE

void cvDFT( const CvArr* src, CvArr* dst, int flags, int nonzero_rows=0 );
</pre><p><dl>
<dt>src<dd>Source array, real or complex.
<dt>dst<dd>Destination array of the same size and same type as the source.
<dt>flags<dd>Transformation flags, a combination of the following values:<br>
              <code>CV_DXT_FORWARD</code> - do forward 1D or 2D transform. The result is not scaled.<br>
              <code>CV_DXT_INVERSE</code> - do inverse 1D or 2D transform. The result is not scaled.
                               <code>CV_DXT_FORWARD</code> and <code>CV_DXT_INVERSE</code> are mutually exclusive,
                               of course.<br>
              <code>CV_DXT_SCALE</code> - scale the result: divide it by the number of array elements.
                                          Usually, it is combined with <code>CV_DXT_INVERSE</code>, and one
                                          may use a shortcut <code>CV_DXT_INV_SCALE</code>.<br>
              <code>CV_DXT_ROWS</code> - do forward or inverse transform of every individual row of the input
                                         matrix. This flag allows user to transform multiple vectors simultaneously and
                                         can be used to decrease the overhead (which is sometimes several times
                                         larger than the processing itself), to do 3D and higher-dimensional
                                         transforms etc.
<dt>nonzero_rows<dd>Number of nonzero rows to in the source array (in case of forward 2d transform),
                    or a number of rows of interest in the destination array (in case of inverse 2d transform).
                    If the value is negative, zero, or greater than the total number of rows, it is ignored.
                    The parameter can be used to speed up 2d convolution/correlation when computing them via DFT.
                    See the sample below.
</dl><p>
The function <code>cvDFT</code> performs forward or inverse transform of
1D or 2D floating-point array:
<pre>
Forward Fourier transform of 1D vector of N elements:
y = F<sup>(N)</sup>&bull;x, where F<sup>(N)</sup><sub>jk</sub>=exp(-i&bull;2Pi&bull;j&bull;k/N), i=sqrt(-1)

Inverse Fourier transform of 1D vector of N elements:
x'= (F<sup>(N)</sup>)<sup>-1</sup>&bull;y = conj(F<sup>(N)</sup>)&bull;y
x = (1/N)&bull;x

Forward Fourier transform of 2D vector of M&times;N elements:
Y = F<sup>(M)</sup>&bull;X&bull;F<sup>(N)</sup>

Inverse Fourier transform of 2D vector of M&times;N elements:
X'= conj(F<sup>(M)</sup>)&bull;Y&bull;conj(F<sup>(N)</sup>)
X = (1/(M&bull;N))&bull;X'
</pre>

<p>In case of real (single-channel) data, the packed format, borrowed from IPL, is used to
to represent a result of forward Fourier transform or input for inverse Fourier transform:

<pre>
Re Y<sub>0,0</sub>      Re Y<sub>0,1</sub>    Im Y<sub>0,1</sub>    Re Y<sub>0,2</sub>     Im Y<sub>0,2</sub>  ...  Re Y<sub>0,N/2-1</sub>   Im Y<sub>0,N/2-1</sub>  Re Y<sub>0,N/2</sub>
Re Y<sub>1,0</sub>      Re Y<sub>1,1</sub>    Im Y<sub>1,1</sub>    Re Y<sub>1,2</sub>     Im Y<sub>1,2</sub>  ...  Re Y<sub>1,N/2-1</sub>   Im Y<sub>1,N/2-1</sub>  Re Y<sub>1,N/2</sub>
Im Y<sub>1,0</sub>      Re Y<sub>2,1</sub>    Im Y<sub>2,1</sub>    Re Y<sub>2,2</sub>     Im Y<sub>2,2</sub>  ...  Re Y<sub>2,N/2-1</sub>   Im Y<sub>2,N/2-1</sub>  Im Y<sub>2,N/2</sub>
............................................................................................
Re Y<sub>M/2-1,0</sub>   Re Y<sub>M-3,1</sub>   Im Y<sub>M-3,1</sub>  Re Y<sub>M-3,2</sub>   Im Y<sub>M-3,2</sub> ...  Re Y<sub>M-3,N/2-1</sub>  Im Y<sub>M-3,N/2-1</sub> Re Y<sub>M-3,N/2</sub>
Im Y<sub>M/2-1,0</sub>   Re Y<sub>M-2,1</sub>   Im Y<sub>M-2,1</sub>  Re Y<sub>M-2,2</sub>   Im Y<sub>M-2,2</sub> ...  Re Y<sub>M-2,N/2-1</sub>  Im Y<sub>M-2,N/2-1</sub> Im Y<sub>M-2,N/2</sub>
Re Y<sub>M/2,0</sub>    Re Y<sub>M-1,1</sub>   Im Y<sub>M-1,1</sub>  Re Y<sub>M-1,2</sub>   Im Y<sub>M-1,2</sub>  ... Re Y<sub>M-1,N/2-1</sub>  Im Y<sub>M-1,N/2-1</sub> Im Y<sub>M-1,N/2</sub>
</pre>

<p>Note: the last column is present if <code>N</code> is even, the last row is present if <code>M</code> is even.</p>
<p>In case of 1D real transform the result looks like the first row of the above matrix</p>

<font color=blue size=4>Computing 2D Convolution using DFT</font></p>
<pre>
   CvMat* A = cvCreateMat( M1, N1, CV_32F );
   CvMat* B = cvCreateMat( M2, N2, A->type );

   // it is also possible to have only abs(M2-M1)+1&times;abs(N2-N1)+1
   // part of the full convolution result
   CvMat* conv = cvCreateMat( A->rows + B->rows - 1, A->cols + B->cols - 1, A->type );

   // initialize A and B
   ...

   int dft_M = cvGetOptimalDFTSize( A->rows + B->rows - 1 );
   int dft_N = cvGetOptimalDFTSize( A->cols + B->cols - 1 );

   CvMat* dft_A = cvCreateMat( dft_M, dft_N, A->type );
   CvMat* dft_B = cvCreateMat( dft_M, dft_N, B->type );
   CvMat tmp;

   // copy A to dft_A and pad dft_A with zeros
   cvGetSubRect( dft_A, &tmp, cvRect(0,0,A->cols,A->rows));
   cvCopy( A, &tmp );
   cvGetSubRect( dft_A, &tmp, cvRect(A->cols,0,dft_A->cols - A->cols,A->rows));
   cvZero( &tmp );
   // no need to pad bottom part of dft_A with zeros because of
   // use nonzero_rows parameter in cvDFT() call below

   cvDFT( dft_A, dft_A, CV_DXT_FORWARD, A->rows );

   // repeat the same with the second array
   cvGetSubRect( dft_B, &tmp, cvRect(0,0,B->cols,B->rows));
   cvCopy( B, &tmp );
   cvGetSubRect( dft_B, &tmp, cvRect(B->cols,0,dft_B->cols - B->cols,B->rows));
   cvZero( &tmp );
   // no need to pad bottom part of dft_B with zeros because of
   // use nonzero_rows parameter in cvDFT() call below

   cvDFT( dft_B, dft_B, CV_DXT_FORWBRD, B->rows );

   cvMulSpectrums( dft_A, dft_B, dft_A, 0 /* or CV_DXT_MUL_CONJ to get correlation
                                             rather than convolution */ );

   cvDFT( dft_A, dft_A, CV_DXT_INV_SCALE, conv->rows ); // calculate only the top part
   cvGetSubRect( dft_A, &tmp, cvRect(0,0,conv->cols,conv->rows) );

   cvCopy( &tmp, conv );
</pre></p>


<hr><h3><a name="decl_cvGetOptimalDFTSize">GetOptimalDFTSize</a></h3>
<p class="Blurb">Returns optimal DFT size for given vector size</p>
<pre>
int cvGetOptimalDFTSize( int size0 );
</pre><p><dl>
<dt>size0<dd>Vector size.
</dl><p>
The function <code>cvGetOptimalDFTSize</code> returns the minimum
number <code>N</code> that is greater to equal to <code>size0</code>, such that DFT of a vector
of size <code>N</code> can be computed fast. In the current implementation
<code>N=2<sup>p</sup>&times;3<sup>q</sup>&times;5<sup>r</sup></code> for some <code>p, q, r</code>.
</p>
<p>The function returns a negative number if <code>size0</code> is too large (very close to <code>INT_MAX</code>)</p>


<hr><h3><a name="decl_cvMulSpectrums">MulSpectrums</a></h3>
<p class="Blurb">Performs per-element multiplication of two Fourier spectrums</p>
<pre>
void cvMulSpectrums( const CvArr* src1, const CvArr* src2, CvArr* dst, int flags );
</pre><p><dl>
<dt>src1<dd>The first source array.
<dt>src2<dd>The second source array.
<dt>dst<dd>The destination array of the same type and the same size of the sources.
<dt>flags<dd>A combination of the following values:<br>
              <code>CV_DXT_ROWS</code> - treat each row of the arrays as a separate spectrum
                                         (see <a href="#decl_cvDFT">cvDFT</a> parameters description).<br>
              <code>CV_DXT_MUL_CONJ</code> - conjugate the second source array before the multiplication.<br>
</dl><p>
The function <code>cvMulSpectrums</code> performs per-element multiplication
of the two CCS-packed or complex matrices that are results of real or complex Fourier transform.
</p><p>
The function, together with <a href="#decl_cvDFT">cvDFT</a>, may be used to calculate convolution
of two arrays fast.
</p>

<hr><h3><a name="decl_cvDCT">DCT</a></h3>
<p class="Blurb">Performs forward or inverse Discrete Cosine transform of 1D or 2D floating-point array</p>
<pre>
#define CV_DXT_FORWARD  0
#define CV_DXT_INVERSE  1
#define CV_DXT_ROWS     4

void cvDCT( const CvArr* src, CvArr* dst, int flags );
</pre><p><dl>
<dt>src<dd>Source array, real 1D or 2D array.
<dt>dst<dd>Destination array of the same size and same type as the source.
<dt>flags<dd>Transformation flags, a combination of the following values:<br>
              <code>CV_DXT_FORWARD</code> - do forward 1D or 2D transform.<br>
              <code>CV_DXT_INVERSE</code> - do inverse 1D or 2D transform.<br>
              <code>CV_DXT_ROWS</code> - do forward or inverse transform of every individual row of the input
                                         matrix. This flag allows user to transform multiple vectors simultaneously and
                                         can be used to decrease the overhead (which is sometimes several times
                                         larger than the processing itself), to do 3D and higher-dimensional
                                         transforms etc.
</dl><p>
The function <code>cvDCT</code> performs forward or inverse transform of
1D or 2D floating-point array:
<pre>
Forward Cosine transform of 1D vector of N elements:
y = C<sup>(N)</sup>&bull;x, where C<sup>(N)</sup><sub>jk</sub>=sqrt((j==0?1:2)/N)&bull;cos(Pi&bull;(2k+1)&bull;j/N)

Inverse Cosine transform of 1D vector of N elements:
x = (C<sup>(N)</sup>)<sup>-1</sup>&bull;y = (C<sup>(N)</sup>)<sup>T</sup>&bull;y

Forward Cosine transform of 2D vector of M&times;N elements:
Y = (C<sup>(M)</sup>)&bull;X&bull;(C<sup>(N)</sup>)<sup>T</sup>

Inverse Cosine transform of 2D vector of M&times;N elements:
X = (C<sup>(M)</sup>)<sup>T</sup>&bull;Y&bull;C<sup>(N)</sup>
</pre>


<hr><h1><a name="cxcore_ds">Dynamic Structures</a></h1>

<hr><h2><a name="cxcore_ds_storages">Memory Storages</a></h2>

<hr><h3><a name="decl_CvMemStorage">CvMemStorage</a></h3>
<p class="Blurb">Growing memory storage</p>
<pre>
typedef struct CvMemStorage
{
    struct CvMemBlock* bottom;/* first allocated block */
    struct CvMemBlock* top; /* the current memory block - top of the stack */
    struct CvMemStorage* parent; /* borrows new blocks from */
    int block_size; /* block size */
    int free_space; /* free space in the <code>top</code> block (in bytes) */
} CvMemStorage;
</pre>
<p>
Memory storage is a low-level structure used to store dynamically growing data structures such as
sequences, contours, graphs, subdivisions etc. It is organized as a list of memory blocks of
equal size - <code>bottom</code> field is the beginning of the list of blocks</code>
and <code>top</code> is the currently used block, but not necessarily the last block of the list. All blocks
between <code>bottom</code> and <code>top</code>, not including the latter, are considered fully ocupied;
and all blocks between <code>top</code> and the last block, not including <code>top</code>,
are considered free and <code>top</code> block itself is partly ocupied - <code>free_space</code>
contains the number of free bytes left in the end of <code>top</code>.
</p><p>New memory buffer that may be allocated explicitly by <a href="#decl_cvMemStorageAlloc">cvMemStorageAlloc</a> function
or implicitly by
higher-level functions, such as <a href="#decl_cvSeqPush">cvSeqPush</a>, <a href="#decl_cvGraphAddEdge">cvGraphAddEdge</a> etc., <code>always</code>
starts in the end of the current block if it fits there. After allocation <code>free_space</code>
is decremented by the size of the allocated buffer plus some padding to keep the proper alignment.
When the allocated buffer does not fit into the available part of <code>top</code>, the next storage
block from the list is taken as <code>top</code> and <code>free_space</code> is reset to the
whole block size prior to the allocation.</p><p>
If there is no more free blocks, a new block is allocated (or borrowed from parent, see
<a href="#decl_cvCreateChildMemStorage">cvCreateChildMemStorage</a>) and added to the end of list. Thus, the storage behaves as a stack
with <code>bottom</code> indicating bottom of the stack and the pair (<code>top</code>, <code>free_space</code>)
indicating top of the stack. The stack top may be saved via <a href="#decl_cvSaveMemStoragePos">cvSaveMemStoragePos</a>,
restored via <a href="#decl_cvRestoreMemStoragePos">cvRestoreMemStoragePos</a> or reset via <a href="#decl_cvClearStorage">cvClearStorage</a>.
</p>


<hr><h3><a name="decl_CvMemBlock">CvMemBlock</a></h3>
<p class="Blurb">Memory storage block</p>
<pre>
typedef struct CvMemBlock
{
    struct CvMemBlock* prev;
    struct CvMemBlock* next;
} CvMemBlock;
</pre>
<p>
The structure <a href="#decl_CvMemBlock">CvMemBlock</a> represents a single block of memory storage.
Actual data of the memory blocks follows the header, that is, the <code>i-th</code> byte of
the memory block can be retrieved with the expression <code>((char*)(mem_block_ptr+1))[i]</code>.
However, normally there is no need to access the storage structure fields directly.
</p>


<hr><h3><a name="decl_CvMemStoragePos">CvMemStoragePos</a></h3>
<p class="Blurb">Memory storage position</p>
<pre>
typedef struct CvMemStoragePos
{
    CvMemBlock* top;
    int free_space;
} CvMemStoragePos;
</pre>
<p>
The structure described below stores the position of the stack top that can be
saved via <a href="#decl_cvSaveMemStoragePos">cvSaveMemStoragePos</a> and restored via <a href="#decl_cvRestoreMemStoragePos">cvRestoreMemStoragePos</a>.</p>


<hr><h3><a name="decl_cvCreateMemStorage">CreateMemStorage</a></h3>
<p class="Blurb">Creates memory storage</p>
<pre>
CvMemStorage* cvCreateMemStorage( int block_size=0 );
</pre><p><dl>
<dt>block_size<dd>Size of the storage blocks in bytes. If it is 0, the block size is set to default value
- currently it is &asymp;64K.
</dl><p>
The function <code>cvCreateMemStorage</code> creates a memory storage and returns pointer
to it. Initially the storage is empty. All fields of the header, except the <code>block_size</code>,
are set to 0.</p>


<hr><h3><a name="decl_cvCreateChildMemStorage">CreateChildMemStorage</a></h3>
<p class="Blurb">Creates child memory storage</p>
<pre>
CvMemStorage* cvCreateChildMemStorage( CvMemStorage* parent );
</pre><p><dl>
<dt>parent<dd>Parent memory storage.
</dl><p>
The function <code>cvCreateChildMemStorage</code> creates a child memory storage that is similar
to simple memory storage except for the differences in the memory
allocation/deallocation mechanism. When a child storage needs a new block to
add to the block list, it tries to get this block from the parent. The first
unoccupied parent block available is taken and excluded from the parent block
list. If no blocks are available, the parent either allocates a block or borrows
one from its own parent, if any. In other words, the chain, or a more complex
structure, of memory storages where every storage is a child/parent of another
is possible. When a child storage is released or even cleared, it returns all
blocks to the parent. In other aspects, the child storage is the same as the simple storage.</p>
<p>
The children storages are useful in the following situation.
Imagine that user needs to process dynamical data resided in some storage and
put the result back to the same storage. With the simplest approach, when temporary
data is resided in the same storage as the input and output data, the storage
will look as following after processing:</p>
<p>
<font color=blue>Dynamic data processing without using child storage</font>
</p>
<p>
<img align="center" src="pics/memstorage1.png" >
</p>
<p>
That is, garbage appears in the middle of the storage.
However, if one creates a child memory storage in the beginning of the processing,
writes temporary data there and releases the child storage in the end, no garbage will
appear in the source/destination storage:</p>
<p><font color=blue>Dynamic data processing using a child storage</font>
</p><p>
<img align="center" src="pics/memstorage2.png" >
</p>


<hr><h3><a name="decl_cvReleaseMemStorage">ReleaseMemStorage</a></h3>
<p class="Blurb">Releases memory storage</p>
<pre>
void cvReleaseMemStorage( CvMemStorage** storage );
</pre><p><dl>
<dt>storage<dd>Pointer to the released storage.
</dl><p>
The function <code>cvReleaseMemStorage</code> deallocates all storage memory blocks or returns
them to the parent, if any. Then it deallocates the storage header and clears
the pointer to the storage. All children of the storage must be released before
the parent is released.</p>


<hr><h3><a name="decl_cvClearMemStorage">ClearMemStorage</a></h3>
<p class="Blurb">Clears memory storage</p>
<pre>
void cvClearMemStorage( CvMemStorage* storage );
</pre><p><dl>
<dt>storage<dd>Memory storage.
</dl><p>
The function <code>cvClearMemStorage</code> resets the top (free space boundary) of the storage
to the very beginning. This function does not deallocate any memory. If the
storage has a parent, the function returns all blocks to the parent.</p>


<hr><h3><a name="decl_cvMemStorageAlloc">MemStorageAlloc</a></h3>
<p class="Blurb">Allocates memory buffer in the storage</p>
<pre>
void* cvMemStorageAlloc( CvMemStorage* storage, size_t size );
</pre><p><dl>
<dt>storage<dd>Memory storage.
<dt>size<dd>Buffer size.
</dl><p>
The function <code>cvMemStorageAlloc</code> allocates memory buffer in the storage. The buffer size
must not exceed the storage block size, otherwise runtime error is raised. The buffer address is
aligned by <code>CV_STRUCT_ALIGN</code> (=<code>sizeof(double)</code> for the moment) bytes.
</p>


<hr><h3><a name="decl_cvMemStorageAllocString">MemStorageAllocString</a></h3>
<p class="Blurb">Allocates text string in the storage</p>
<pre>
typedef struct CvString
{
    int len;
    char* ptr;
}
CvString;

CvString cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, int len=-1 );
</pre><p><dl>
<dt>storage<dd>Memory storage.
<dt>ptr<dd>The string.
<dt>len<dd>Length of the string (not counting the ending '\0'). If the parameter is negative,
           the function computes the length.
</dl><p>
The function <code>cvMemStorageAllocString</code> creates copy of the
string in the memory storage. It returns the structure that contains user-passed or computed length
of the string and pointer to the copied string.
</p>


<hr><h3><a name="decl_cvSaveMemStoragePos">SaveMemStoragePos</a></h3>
<p class="Blurb">Saves memory storage position</p>
<pre>
void cvSaveMemStoragePos( const CvMemStorage* storage, CvMemStoragePos* pos );
</pre><p><dl>
<dt>storage<dd>Memory storage.
<dt>pos<dd>The output position of the storage top.
</dl><p>
The function <code>cvSaveMemStoragePos</code> saves the current position of the storage top to
the parameter <code>pos</code>. The function <code>cvRestoreMemStoragePos</code> can further retrieve
this position.</p>


<hr><h3><a name="decl_cvRestoreMemStoragePos">RestoreMemStoragePos</a></h3>
<p class="Blurb">Restores memory storage position</p>
<pre>
void cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos );
</pre><p><dl>
<dt>storage<dd>Memory storage.
<dt>pos<dd>New storage top position.
</dl><p>
The function <code>cvRestoreMemStoragePos</code> restores the position of the storage top from
the parameter <code>pos</code>. This function and The function <code>cvClearMemStorage</code> are the
only methods to release memory occupied in memory blocks.
Note again that there is no way to free memory in the middle of the occupied part of the storage.
</p>


<hr><h2><a name="cxcore_ds_sequences">Sequences</a></h2>

<hr><h3><a name="decl_CvSeq">CvSeq</a></h3>
<p class="Blurb">Growable sequence of elements</p>
<pre>
#define CV_SEQUENCE_FIELDS() \
    int flags; /* micsellaneous flags */ \
    int header_size; /* size of sequence header */ \
    struct CvSeq* h_prev; /* previous sequence */ \
    struct CvSeq* h_next; /* next sequence */ \
    struct CvSeq* v_prev; /* 2nd previous sequence */ \
    struct CvSeq* v_next; /* 2nd next sequence */ \
    int total; /* total number of elements */ \
    int elem_size;/* size of sequence element in bytes */ \
    char* block_max;/* maximal bound of the last block */ \
    char* ptr; /* current write pointer */ \
    int delta_elems; /* how many elements allocated when the sequence grows (sequence granularity) */ \
    CvMemStorage* storage; /* where the seq is stored */ \
    CvSeqBlock* free_blocks; /* free blocks list */ \
    CvSeqBlock* first; /* pointer to the first sequence block */


typedef struct CvSeq
{
    CV_SEQUENCE_FIELDS()
} CvSeq;
</pre>
<p>
The structure <a href="#decl_CvSeq">CvSeq</a> is a base for all of OpenCV dynamic data structures.</p>
<p>Such an unusual definition via a helper macro simplifies the extension of the structure
<a href="#decl_CvSeq">CvSeq</a> with additional parameters.
To extend <a href="#decl_CvSeq">CvSeq</a> the user may define a new structure and
put user-defined fields after all <a href="#decl_CvSeq">CvSeq</a> fields that are included via the macro
<code>CV_SEQUENCE_FIELDS()</code>.</p>
<p>There are two types of sequences - dense and sparse. Base type for dense sequences is <a href="#decl_CvSeq">CvSeq</a>
and such sequences are used to represent growable 1d arrays - vectors, stacks, queues, deques.
They have no gaps in the middle - if an element is removed from the middle or inserted into the middle
of the sequence the elements from the closer end are shifted.
Sparse sequences have <a href="#decl_CvSet">CvSet</a> base
class and they are discussed later in more details. They are sequences of nodes each of those may be
either occupied or free as indicated by the node flag. Such sequences are used for unordered data
structures such as sets of elements, graphs, hash tables etc.</p>

<p>The field <code>header_size</code> contains the actual size of the
sequence header and should be greater or equal to <code>sizeof(CvSeq)</code>.</p><p>The fields
<code>h_prev, h_next, v_prev, v_next</code> can be used to create hierarchical structures
from separate sequences. The fields <code>h_prev</code> and <code>h_next</code> point to the previous and
the next sequences on the same hierarchical level while the fields <code>v_prev</code> and
<code>v_next</code> point to the previous and the next sequence in the vertical direction,
that is, parent and its first child. But these are just names and the pointers
can be used in a different way.</p><p>The field <code>first</code> points to the first sequence
block, whose structure is described below.</p>
<p>The field <code>total</code> contains the actual number of dense sequence elements and
number of allocated nodes in sparse sequence.</p>
<p>The field <code>flags</code>contain the particular dynamic type
signature (<code>CV_SEQ_MAGIC_VAL</code> for dense sequences and <code>CV_SET_MAGIC_VAL</code> for sparse sequences)
in the highest 16 bits and miscellaneous information about the sequence.
The lowest <code>CV_SEQ_ELTYPE_BITS</code> bits contain the ID of the
element type. Most of sequence processing functions do not use element type
but element size stored in <code>elem_size</code>.
If sequence contains the numeric data of one of <a href="#decl_CvMat">CvMat</a> type
then the element type matches to the corresponding <a href="#decl_CvMat">CvMat</a> element type, e.g.
CV_32SC2 may be used for sequence of 2D points, CV_32FC1 for sequences of floating-point values etc.
<code>CV_SEQ_ELTYPE(seq_header_ptr)</code> macro retrieves the type of sequence elements.
Processing function that work with numerical sequences check that <code>elem_size</code> is equal
to the calculated from the type element size.
Besides <a href="#decl_CvMat">CvMat</a> compatible types, there are few extra element types defined
in <a href="#decl_cvtypes.h">cvtypes.h</a> header:</p>
<p><font color=blue>Standard Types of Sequence Elements</font></p>
<pre>
    #define CV_SEQ_ELTYPE_POINT          CV_32SC2  /* (x,y) */
    #define CV_SEQ_ELTYPE_CODE           CV_8UC1   /* freeman code: 0..7 */
    #define CV_SEQ_ELTYPE_GENERIC        0 /* unspecified type of sequence elements */
    #define CV_SEQ_ELTYPE_PTR            CV_USRTYPE1 /* =6 */
    #define CV_SEQ_ELTYPE_PPOINT         CV_SEQ_ELTYPE_PTR  /* &elem: pointer to element of other sequence */
    #define CV_SEQ_ELTYPE_INDEX          CV_32SC1  /* #elem: index of element of some other sequence */
    #define CV_SEQ_ELTYPE_GRAPH_EDGE     CV_SEQ_ELTYPE_GENERIC  /* &next_o, &next_d, &vtx_o, &vtx_d */
    #define CV_SEQ_ELTYPE_GRAPH_VERTEX   CV_SEQ_ELTYPE_GENERIC  /* first_edge, &(x,y) */
    #define CV_SEQ_ELTYPE_TRIAN_ATR      CV_SEQ_ELTYPE_GENERIC  /* vertex of the binary tree   */
    #define CV_SEQ_ELTYPE_CONNECTED_COMP CV_SEQ_ELTYPE_GENERIC  /* connected component  */
    #define CV_SEQ_ELTYPE_POINT3D        CV_32FC3  /* (x,y,z)  */
</pre>
<p>
The next <code>CV_SEQ_KIND_BITS</code> bits specify the kind of the sequence:</p>
<p><font color=blue>Standard Kinds of Sequences</font></p>
<pre>
    /* generic (unspecified) kind of sequence */
    #define CV_SEQ_KIND_GENERIC     (0 &lt;&lt; CV_SEQ_ELTYPE_BITS)

    /* dense sequence suntypes */
    #define CV_SEQ_KIND_CURVE       (1 &lt;&lt; CV_SEQ_ELTYPE_BITS)
    #define CV_SEQ_KIND_BIN_TREE    (2 &lt;&lt; CV_SEQ_ELTYPE_BITS)

    /* sparse sequence (or set) subtypes */
    #define CV_SEQ_KIND_GRAPH       (3 &lt;&lt; CV_SEQ_ELTYPE_BITS)
    #define CV_SEQ_KIND_SUBDIV2D    (4 &lt;&lt; CV_SEQ_ELTYPE_BITS)
</pre>
<p>
The remaining bits are used to identify different features specific to certain
sequence kinds and element types. For example, curves made of points (
<code>CV_SEQ_KIND_CURVE|CV_SEQ_ELTYPE_POINT</code> ), together with the flag
<code>CV_SEQ_FLAG_CLOSED</code> belong to the type <code>CV_SEQ_POLYGON</code> or, if other flags are
used, to its subtype. Many contour processing functions check the type of the input
sequence and report an error if they do not support this type. The file
<a href="#decl_cvtypes.h">cvtypes.h</a> stores the complete list of all supported predefined sequence types
and helper macros designed to get the sequence type of other properties.
Below follows the definition of the building block of sequences.</p>


<hr><h3><a name="decl_CvSeqBlock">CvSeqBlock</a></h3>
<p class="Blurb">Continuous sequence block</p>
<pre>
typedef struct CvSeqBlock
{
    struct CvSeqBlock* prev; /* previous sequence block */
    struct CvSeqBlock* next; /* next sequence block */
    int start_index; /* index of the first element in the block +
    sequence->first->start_index */
    int count; /* number of elements in the block */
    char* data; /* pointer to the first element of the block */
} CvSeqBlock;
</pre>
<p>
Sequence blocks make up a circular double-linked list, so the pointers <code>prev</code> and
<code>next</code> are never <code>NULL</code> and point to the previous and the next sequence blocks
within the sequence. It means that <code>next</code> of the last block is the first block and
<code>prev</code> of the first block is the last block. The fields <code>start_index</code> and <code>count</code> help
to track the block location within the sequence. For example, if the sequence
consists of 10 elements and splits into three blocks of 3, 5, and 2 elements,
and the first block has the parameter <code>start_index = 2</code>, then pairs <code>(start_index, count)</code>
for the sequence blocks are <code>(2,3), (5, 5)</code>, and <code>(10, 2)</code>
correspondingly. The parameter <code>start_index</code> of the first block is usually <code>0</code>
unless some elements have been inserted at the beginning of the sequence.
</p>


<hr><h3><a name="decl_CvSlice">CvSlice</a></h3>
<p class="Blurb">A sequence slice</p>
<pre>
typedef struct CvSlice
{
    int start_index;
    int end_index;
} CvSlice;

inline CvSlice cvSlice( int start, int end );
#define CV_WHOLE_SEQ_END_INDEX 0x3fffffff
#define CV_WHOLE_SEQ  cvSlice(0, CV_WHOLE_SEQ_END_INDEX)

/* calculates the sequence slice length */
int cvSliceLength( CvSlice slice, const CvSeq* seq );
</pre>
<p>
Some of functions that operate on sequences take <code>CvSlice slice</code> parameter that is
often set to the whole sequence (CV_WHOLE_SEQ) by default. Either of the <code>start_index</code>
and <code>end_index</code> may be negative or exceed the sequence length, <code>start_index</code>
is inclusive, <code>end_index</code> is exclusive boundary. If they are equal, the slice is considered
empty (i.e. contains no elements). Because sequences are treated as circular structures,
the slice may select a few elements in the end of a sequence followed by a few elements in the beginning
of the sequence, for example, <code>cvSlice(-2, 3)</code> in case of 10-element sequence will select 5-element slice,
containing pre-last (8th), last (9th), the very first (0th), second (1th) and third (2nd) elements.
The functions normalize the slice argument in the following way: first, <a href="#decl_CvSlice">cvSliceLength</a>
is called to determine the length of the slice, then, <code>start_index</code> of the slice is
normalized similarly to the argument of <a href="#decl_cvGetSeqElem">cvGetSeqElem</a>
(i.e. negative indices are allowed).
The actual slice to process starts at the normalized <code>start_index</code>
and lasts <a href="#decl_CvSlice">cvSliceLength</a> elements
(again, assuming the sequence is a circular structure).
</p>

<p>If a function does not take slice argument, but you want to process only a part of the sequence,
the sub-sequence may be extracted using <a href="#decl_cvSeqSlice">cvSeqSlice</a> function,
or stored as into a continuous buffer with <a href="#decl_cvCvtSeqToArray">cvCvtSeqToArray</a>
(optionally, followed by <a href="#decl_cvMakeSeqHeaderForArray">cvMakeSeqHeaderForArray</a>.
</p>


<hr><h3><a name="decl_cvCreateSeq">CreateSeq</a></h3>
<p class="Blurb">Creates sequence</p>
<pre>
CvSeq* cvCreateSeq( int seq_flags, int header_size,
                    int elem_size, CvMemStorage* storage );
</pre><p><dl>
<dt>seq_flags<dd>Flags of the created sequence. If the sequence is not passed to any
function working with a specific type of sequences, the sequence value may be
set to 0, otherwise the appropriate type must be selected from the list of
predefined sequence types.
<dt>header_size<dd>Size of the sequence header; must be greater or equal to
<code>sizeof(CvSeq)</code>. If a specific type or its extension is indicated, this type must
fit the base type header.
<dt>elem_size<dd>Size of the sequence elements in bytes. The size must be consistent
with the sequence type. For example, for a sequence of points to be created, the
element type <code>CV_SEQ_ELTYPE_POINT</code> should be specified and the parameter <code>elem_size</code>
must be equal to <code>sizeof(CvPoint)</code>.
<dt>storage<dd>Sequence location.
</dl><p>
The function <code>cvCreateSeq</code> creates a sequence and returns the pointer to it. The
function allocates the sequence header in the storage block as one continuous
chunk and sets the structure fields <code>flags</code>, <code>elem_size</code>, <code>header_size</code> and <code>storage</code> to
passed values, sets <code>delta_elems</code> to the default value (that may be reassigned using
<a href="#decl_cvSetSeqBlockSize">cvSetSeqBlockSize</a> function), and clears other header fields,
including the space after the first <code>sizeof(CvSeq)</code> bytes.</p>


<hr><h3><a name="decl_cvSetSeqBlockSize">SetSeqBlockSize</a></h3>
<p class="Blurb">Sets up sequence block size</p>
<pre>
void cvSetSeqBlockSize( CvSeq* seq, int delta_elems );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>delta_elems<dd>Desirable sequence block size in elements.
</dl><p>
The function <code>cvSetSeqBlockSize</code> affects memory allocation granularity.
When the free space in the sequence buffers has run out, the function allocates the space
for <code>delta_elems</code> sequence elements. If this block immediately follows the one
previously allocated, the two blocks are concatenated, otherwise, a new sequence
block is created. Therefore, the bigger the parameter is, the lower the possible sequence
fragmentation, but the more space in the storage is wasted. When the
sequence is created, the parameter <code>delta_elems</code> is set to the default value &asymp;1K.
The function can be called any time after the sequence is created and affects
future allocations. The function can modify the passed value of the parameter to
meet the memory storage constraints.
</p>


<hr><h3><a name="decl_cvSeqPush">SeqPush</a></h3>
<p class="Blurb">Adds element to sequence end</p>
<pre>
char* cvSeqPush( CvSeq* seq, void* element=NULL );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>element<dd>Added element.
</dl><p>
The function <code>cvSeqPush</code> adds an element to the end of sequence and retuns pointer
to the allocated element. If the input <code>element</code> is NULL,
the function simply allocates a space for one more element.</p>
<p>The following code demonstrates how to create a new sequence using this function:</p>
<pre>
CvMemStorage* storage = cvCreateMemStorage(0);
CvSeq* seq = cvCreateSeq( CV_32SC1, /* sequence of integer elements */
                          sizeof(CvSeq), /* header size - no extra fields */
                          sizeof(int), /* element size */
                          storage /* the container storage */ );
int i;
for( i = 0; i &lt; 100; i++ )
{
    int* added = (int*)cvSeqPush( seq, &i );
    printf( "%d is added\n", *added );
}

...
/* release memory storage in the end */
cvReleaseMemStorage( &storage );
</pre>
<p>
The function <code>cvSeqPush</code> has O(1) complexity, but there is a faster method for
writing large sequences (see <a href="#decl_cvStartWriteSeq">cvStartWriteSeq</a> and related functions).
</p>

<hr><h3><a name="decl_cvSeqPop">SeqPop</a></h3>
<p class="Blurb">Removes element from sequence end</p>
<pre>
void cvSeqPop( CvSeq* seq, void* element=NULL );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>element<dd>Optional parameter. If the pointer is not zero, the function copies the
removed element to this location.
</dl><p>
The function <code>cvSeqPop</code> removes an element from the sequence. The function reports
an error if the sequence is already empty. The function has O(1) complexity. </p>


<hr><h3><a name="decl_cvSeqPushFront">SeqPushFront</a></h3>
<p class="Blurb">Adds element to sequence beginning</p>
<pre>
char* cvSeqPushFront( CvSeq* seq, void* element=NULL );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>element<dd>Added element.
</dl><p>
The function <code>cvSeqPushFront</code> is similar to <a href="#decl_cvSeqPush">cvSeqPush</a> but it adds the new element
to the beginning of the sequence. The function has O(1) complexity.
</p>


<hr><h3><a name="decl_cvSeqPopFront">SeqPopFront</a></h3>
<p class="Blurb">Removes element from sequence beginning</p>
<pre>
void cvSeqPopFront( CvSeq* seq, void* element=NULL );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>element<dd>Optional parameter. If the pointer is not zero, the function copies the
removed element to this location.
</dl><p>
The function <code>cvSeqPopFront</code> removes an element from the beginning of the sequence.
The function reports an error if the sequence is already empty. The function has O(1) complexity. </p>


<hr><h3><a name="decl_cvSeqPushMulti">SeqPushMulti</a></h3>
<p class="Blurb">Pushes several elements to the either end of sequence</p>
<pre>
void cvSeqPushMulti( CvSeq* seq, void* elements, int count, int in_front=0 );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>elements<dd>Added elements.
<dt>count<dd>Number of elements to push.
<dt>in_front<dd>The flags specifying the modified sequence end:<br>
                CV_BACK (=0) - the elements are added to the end of sequence<br>
                CV_FRONT(!=0) - the elements are added to the beginning of sequence<br>
</dl><p>
The function <code>cvSeqPushMulti</code> adds several elements to either end of the sequence.
The elements are added to the sequence in the same order as they are arranged in the
input array but they can fall into different sequence blocks.</p>


<hr><h3><a name="decl_cvSeqPopMulti">SeqPopMulti</a></h3>
<p class="Blurb">Removes several elements from the either end of sequence</p>
<pre>
void cvSeqPopMulti( CvSeq* seq, void* elements, int count, int in_front=0 );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>elements<dd>Removed elements.
<dt>count<dd>Number of elements to pop.
<dt>in_front<dd>The flags specifying the modified sequence end:<br>
                CV_BACK (=0) - the elements are removed from the end of sequence<br>
                CV_FRONT(!=0) - the elements are removed from the beginning of sequence<br>
</dl><p>
The function <code>cvSeqPopMulti</code> removes several elements from either end of the sequence.
If the number of the elements to be removed exceeds the total number of elements
in the sequence, the function removes as many elements as possible.</p>


<hr><h3><a name="decl_cvSeqInsert">SeqInsert</a></h3>
<p class="Blurb">Inserts element in sequence middle</p>
<pre>
char* cvSeqInsert( CvSeq* seq, int before_index, void* element=NULL );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>before_index<dd>Index before which the element is inserted. Inserting before 0 (the minimal allowed value
of the parameter) is equal to <a href="#decl_cvSeqPushFront">cvSeqPushFront</a> and inserting before <code>seq->total</code> (the maximal
allowed value of the parameter) is equal to <a href="#decl_cvSeqPush">cvSeqPush</a>.
<dt>element<dd>Inserted element.
</dl><p>
The function <code>cvSeqInsert</code> shifts the sequence elements from the inserted position
to the nearest end of the sequence and copies the <code>element</code> content there if
the pointer is not NULL. The function returns pointer to the inserted element.</p>


<hr><h3><a name="decl_cvSeqRemove">SeqRemove</a></h3>
<p class="Blurb">Removes element from sequence middle</p>
<pre>
void cvSeqRemove( CvSeq* seq, int index );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>index<dd>Index of removed element.
</dl><p>
The function <code>cvSeqRemove</code> removes elements with the given index. If the index is
out of range the function reports an error.
An attempt to remove an element from an empty sequence is a
partitial case of this situation. The function removes an element by shifting the
sequence elements between the nearest end of the sequence and the <code>index</code>-th position, not
counting the latter.</p>


<hr><h3><a name="decl_cvClearSeq">ClearSeq</a></h3>
<p class="Blurb">Clears sequence</p>
<pre>
void cvClearSeq( CvSeq* seq );
</pre><p><dl>
<dt>seq<dd>Sequence.
</dl><p>
The function <code>cvClearSeq</code> removes all elements from the sequence. The function does not return the
memory to the storage, but this memory is reused later when new elements are added
to the sequence. This function time complexity is <code>O(1)</code>.


<hr><h3><a name="decl_cvGetSeqElem">GetSeqElem</a></h3>
<p class="Blurb">Returns pointer to sequence element by its index</p>
<pre>
char* cvGetSeqElem( const CvSeq* seq, int index );
#define CV_GET_SEQ_ELEM( TYPE, seq, index )  (TYPE*)cvGetSeqElem( (CvSeq*)(seq), (index) )
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>index<dd>Index of element.
</dl><p>
The function <code>cvGetSeqElem</code> finds the element with the given index in the sequence
and returns the pointer to it. If the element is not found,
the function returns 0. The function supports negative indices, where -1 stands
for the last sequence element, -2 stands for the one before last, etc. If the
sequence is most likely to consist of a single sequence block or the desired
element is likely to be located in the first block, then the macro
<code>CV_GET_SEQ_ELEM( elemType, seq, index )</code> should be used, where the parameter
<code>elemType</code> is the type of sequence elements ( <a href="#decl_CvPoint">CvPoint</a> for example), the parameter
<code>seq</code> is a sequence, and the parameter <code>index</code> is the index of the desired element.
The macro checks first whether the desired element belongs to the first block of
the sequence and returns it if it does, otherwise the macro calls the main
function <code>GetSeqElem</code>. Negative indices always cause the <a href="#decl_cvGetSeqElem">cvGetSeqElem</a> call.
The function has O(1) time complexity assuming that number of blocks is much smaller than the
number of elements.</p>


<hr><h3><a name="decl_cvSeqElemIdx">SeqElemIdx</a></h3>
<p class="Blurb">Returns index of concrete sequence element</p>
<pre>
int cvSeqElemIdx( const CvSeq* seq, const void* element, CvSeqBlock** block=NULL );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>element<dd>Pointer to the element within the sequence.
<dt>block<dd>Optional argument. If the pointer is not <code>NULL</code>, the address of the
sequence block that contains the element is stored in this location.
</dl><p>
The function <code>cvSeqElemIdx</code> returns the index of a sequence element or a negative
number if the element is not found.</p>


<hr><h3><a name="decl_cvCvtSeqToArray">CvtSeqToArray</a></h3>
<p class="Blurb">Copies sequence to one continuous block of memory</p>
<pre>
void* cvCvtSeqToArray( const CvSeq* seq, void* elements, CvSlice slice=CV_WHOLE_SEQ );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>elements<dd>Pointer to the destination array that must be large enough.
    It should be a pointer to data, not a matrix header.
<dt>slice<dd>The sequence part to copy to the array.
</dl><p>
The function <code>cvCvtSeqToArray</code> copies the entire sequence or subsequence to the
specified buffer and returns the pointer to the buffer.</p>


<hr><h3><a name="decl_cvMakeSeqHeaderForArray">MakeSeqHeaderForArray</a></h3>
<p class="Blurb">Constructs sequence from array</p>
<pre>
CvSeq* cvMakeSeqHeaderForArray( int seq_type, int header_size, int elem_size,
                                void* elements, int total,
                                CvSeq* seq, CvSeqBlock* block );
</pre><p><dl>
<dt>seq_type<dd>Type of the created sequence.
<dt>header_size<dd>Size of the header of the sequence. Parameter sequence must point to
the structure of that size or greater size.
<dt>elem_size<dd>Size of the sequence element.
<dt>elements<dd>Elements that will form a sequence.
<dt>total<dd>Total number of elements in the sequence. The number of array elements
must be equal to the value of this parameter.
<dt>seq<dd>Pointer to the local variable that is used as the sequence header.
<dt>block<dd>Pointer to the local variable that is the header of the single sequence
block.
</dl><p>
The function <code>cvMakeSeqHeaderForArray</code> initializes sequence header for array.
The sequence header as well as the sequence block are allocated by the user (for example, on stack).
No data is copied by the function. The resultant sequence will consists of a single block and have
NULL storage pointer, thus, it is possible to read its elements, but the attempts to
add elements to the sequence will raise an error in most cases.</p>


<hr><h3><a name="decl_cvSeqSlice">SeqSlice</a></h3>
<p class="Blurb">Makes separate header for the sequence slice</p>
<pre>
CvSeq* cvSeqSlice( const CvSeq* seq, CvSlice slice,
                   CvMemStorage* storage=NULL, int copy_data=0 );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>slice<dd>The part of the sequence to extract.
<dt>storage<dd>The destination storage to keep the new sequence header and the copied data if any.
               If it is NULL, the function uses the storage containing the input sequence.
<dt>copy_data<dd>The flag that indicates whether to copy the elements of the extracted slice
                 (<code>copy_data</code>!=0) or not (<code>copy_data</code>=0)
</dl><p>
The function <code>cvSeqSlice</code> creates a sequence
that represents the specified slice of the input sequence. The new sequence either shares the elements
with the original sequence or has own copy of the elements.
So if one needs to process a part of sequence but the processing function does not have a slice parameter,
the required sub-sequence may be extracted using this function.
</p>


<hr><h3><a name="decl_cvCloneSeq">CloneSeq</a></h3>
<p class="Blurb">Creates a copy of sequence</p>
<pre>
CvSeq* cvCloneSeq( const CvSeq* seq, CvMemStorage* storage=NULL );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>storage<dd>The destination storage to keep the new sequence header and the copied data if any.
               If it is NULL, the function uses the storage containing the input sequence.
</dl><p>
The function <code>cvCloneSeq</code> makes a complete copy of the input sequence and returns it.
The call <code><a href="#decl_cvCloneSeq">cvCloneSeq</a>( seq, storage )</code> is equivalent to
<code><a href="#decl_cvSeqSlice">cvSeqSlice</a>( seq, CV_WHOLE_SEQ, storage, 1 )</code>
</p>


<hr><h3><a name="decl_cvSeqRemoveSlice">SeqRemoveSlice</a></h3>
<p class="Blurb">Removes sequence slice</p>
<pre>
void cvSeqRemoveSlice( CvSeq* seq, CvSlice slice );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>slice<dd>The part of the sequence to remove.
</dl><p>
The function <code>cvSeqRemoveSlice</code> removes slice from the sequence.</p>


<hr><h3><a name="decl_cvSeqInsertSlice">SeqInsertSlice</a></h3>
<p class="Blurb">Inserts array in the middle of sequence</p>
<pre>
void cvSeqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>slice<dd>The part of the sequence to remove.
<dt>from_arr<dd>The array to take elements from.
</dl><p>
The function <code>cvSeqInsertSlice</code> inserts all <code>from_arr</code>
array elements at the specified position of the sequence. The array <code>from_arr</code>
can be a matrix or another sequence.</p>


<hr><h3><a name="decl_cvSeqInvert">SeqInvert</a></h3>
<p class="Blurb">Reverses the order of sequence elements</p>
<pre>
void cvSeqInvert( CvSeq* seq );
</pre><p><dl>
<dt>seq<dd>Sequence.
</dl><p>
The function <code>cvSeqInvert</code> reverses the sequence in-place - makes the first element go last,
the last element go first etc.</p>


<hr><h3><a name="decl_cvSeqSort">SeqSort</a></h3>
<p class="Blurb">Sorts sequence element using the specified comparison function</p>
<pre>
/* a &lt; b ? -1 : a > b ? 1 : 0 */
typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);

void cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata=NULL );
</pre><p><dl>
<dt>seq<dd>The sequence to sort
<dt>func<dd>The comparison function that returns negative, zero or positive value depending
            on the elements relation (see the above declaration and the example below) -
            similar function is used by <code>qsort</code> from C runline except that in the latter
            <code>userdata</code> is not used
<dt>userdata<dd>The user parameter passed to the compasion function;
                helps to avoid global variables in some cases.
</dl><p>
The function <code>cvSeqSort</code> sorts the sequence in-place using the specified criteria.
Below is the example of the function use:</p>
<pre>
/* Sort 2d points in top-to-bottom left-to-right order */
static int cmp_func( const void* _a, const void* _b, void* userdata )
{
    CvPoint* a = (CvPoint*)_a;
    CvPoint* b = (CvPoint*)_b;
    int y_diff = a->y - b->y;
    int x_diff = a->x - b->x;
    return y_diff ? y_diff : x_diff;
}

...

CvMemStorage* storage = cvCreateMemStorage(0);
CvSeq* seq = cvCreateSeq( CV_32SC2, sizeof(CvSeq), sizeof(CvPoint), storage );
int i;

for( i = 0; i &lt; 10; i++ )
{
    CvPoint pt;
    pt.x = rand() % 1000;
    pt.y = rand() % 1000;
    cvSeqPush( seq, &pt );
}

cvSeqSort( seq, cmp_func, 0 /* userdata is not used here */ );

/* print out the sorted sequence */
for( i = 0; i &lt; seq->total; i++ )
{
    CvPoint* pt = (CvPoint*)cvSeqElem( seq, i );
    printf( "(%d,%d)\n", pt->x, pt->y );
}

cvReleaseMemStorage( &storage );
</pre>



<hr><h3><a name="decl_cvSeqSearch">SeqSearch</a></h3>
<p class="Blurb">Searches element in sequence</p>
<pre>
/* a &lt; b ? -1 : a > b ? 1 : 0 */
typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);

char* cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func,
                   int is_sorted, int* elem_idx, void* userdata=NULL );
</pre><p><dl>
<dt>seq<dd>The sequence
<dt>elem<dd>The element to look for
<dt>func<dd>The comparison function that returns negative, zero or positive value depending
            on the elements relation (see also <a href="#decl_cvSeqSort">cvSeqSort</a>).
<dt>is_sorted<dd>Whether the sequence is sorted or not.
<dt>elem_idx<dd>Output parameter; index of the found element.
<dt>userdata<dd>The user parameter passed to the compasion function;
                helps to avoid global variables in some cases.
</dl><p>
The function <code>cvSeqSearch</code> searches the element in the sequence.
If the sequence is sorted, binary O(log(N)) search is used, otherwise, a simple linear search is used.
If the element is not found, the function returns NULL pointer and the index is set to the number of
sequence elements if the linear search is used, and to the smallest index <code>i, seq(i)&gt;elem</code>.
</p>


<hr><h3><a name="decl_cvStartAppendToSeq">StartAppendToSeq</a></h3>
<p class="Blurb">Initializes process of writing data to sequence</p>
<pre>
void cvStartAppendToSeq( CvSeq* seq, CvSeqWriter* writer );
</pre><p><dl>
<dt>seq<dd>Pointer to the sequence.
<dt>writer<dd>Writer state; initialized by the function.
</dl><p>
The function <code>cvStartAppendToSeq</code> initializes the process of writing data to the sequence.
Written elements are added to the end of the sequence by <code>CV_WRITE_SEQ_ELEM( written_elem, writer )</code> macro.
Note that during the writing process other operations on the sequence may yield incorrect result or
even corrupt the sequence (see description of <a href="#decl_cvFlushSeqWriter">cvFlushSeqWriter</a> that helps to avoid
some of these problems).</p>


<hr><h3><a name="decl_cvStartWriteSeq">StartWriteSeq</a></h3>
<p class="Blurb">Creates new sequence and initializes writer for it</p>
<pre>
void cvStartWriteSeq( int seq_flags, int header_size, int elem_size,
                      CvMemStorage* storage, CvSeqWriter* writer );
</pre><p><dl>
<dt>seq_flags<dd>Flags of the created sequence. If the sequence is not passed to any
function working with a specific type of sequences, the sequence value may be
equal to 0, otherwise the appropriate type must be selected from the list of
predefined sequence types.
<dt>header_size<dd>Size of the sequence header. The parameter value may not be less than
<code>sizeof(CvSeq)</code>. If a certain type or extension is specified, it must fit the
base type header.
<dt>elem_size<dd>Size of the sequence elements in bytes; must be consistent with the
sequence type. For example, if the sequence of points is created (element type
<code>CV_SEQ_ELTYPE_POINT</code> ), then the parameter elem_size must be equal to
<code>sizeof(CvPoint)</code>.
<dt>storage<dd>Sequence location.
<dt>writer<dd>Writer state; initialized by the function.
</dl><p>
The function <code>cvStartWriteSeq</code> is a composition of <a href="#decl_cvCreateSeq">cvCreateSeq</a> and <a href="#decl_cvStartAppendToSeq">cvStartAppendToSeq</a>.
The pointer to the created sequence is stored at <code>writer->seq</code> and is also returned
by <a href="#decl_cvEndWriteSeq">cvEndWriteSeq</a> function that should be called in the end.</p>


<hr><h3><a name="decl_cvEndWriteSeq">EndWriteSeq</a></h3>
<p class="Blurb">Finishes process of writing sequence</p>
<pre>
CvSeq* cvEndWriteSeq( CvSeqWriter* writer );
</pre><p><dl>
<dt>writer<dd>Writer state
</dl><p>
The function <code>cvEndWriteSeq</code> finishes the writing process and returns the pointer to
the written sequence. The function also truncates the last incomplete sequence block to
return the remaining part of the block to the memory storage. After that the sequence
can be read and modified safely.</p>


<hr><h3><a name="decl_cvFlushSeqWriter">FlushSeqWriter</a></h3>
<p class="Blurb">Updates sequence headers from the writer state</p>
<pre>
void cvFlushSeqWriter( CvSeqWriter* writer );
</pre><p><dl>
<dt>writer<dd>Writer state
</dl><p>
The function <code>cvFlushSeqWriter</code> is intended to enable the user to read sequence
elements, whenever required, during the writing process, e.g., in order to check
specific conditions. The function updates the sequence headers to make reading
from the sequence possible. The writer is not closed, however, so that the
writing process can be continued any time. In some algorithm requires often flush'es,
consider using <a href="#decl_cvSeqPush">cvSeqPush</a> instead.</p>


<hr><h3><a name="decl_cvStartReadSeq">StartReadSeq</a></h3>
<p class="Blurb">Initializes process of sequential reading from sequence</p>
<pre>
void cvStartReadSeq( const CvSeq* seq, CvSeqReader* reader, int reverse=0 );
</pre><p><dl>
<dt>seq<dd>Sequence.
<dt>reader<dd>Reader state; initialized by the function.
<dt>reverse<dd>Determines the direction of the sequence traversal. If <code>reverse</code> is 0,
the reader is positioned at the first sequence element, otherwise it is positioned at the last
element.
</dl><p>
The function <code>cvStartReadSeq</code> initializes the reader state. After that all the
sequence elements from the first down to the last one can be read by subsequent
calls of the macro <code>CV_READ_SEQ_ELEM( read_elem, reader )</code> in case of forward reading
and by using <code>CV_REV_READ_SEQ_ELEM( read_elem, reader )</code> in case of reversed reading.
Both macros put the sequence element to <code>read_elem</code> and move the
reading pointer toward the next element.
A circular structure of sequence blocks is used for the reading process, that
is, after the last element has been read by the macro <code>CV_READ_SEQ_ELEM</code>, the
first element is read when the macro is called again. The same applies to
<code>CV_REV_READ_SEQ_ELEM </code>. There is no function to finish the reading process,
since it neither changes the sequence nor creates any temporary buffers. The reader
field <code>ptr</code> points to the current element of the sequence that is to be read
next. The code below demonstrates how to use sequence writer and reader.</p>
<pre>
CvMemStorage* storage = cvCreateMemStorage(0);
CvSeq* seq = cvCreateSeq( CV_32SC1, sizeof(CvSeq), sizeof(int), storage );
CvSeqWriter writer;
CvSeqReader reader;
int i;

cvStartAppendToSeq( seq, &writer );
for( i = 0; i &lt; 10; i++ )
{
    int val = rand()%100;
    CV_WRITE_SEQ_ELEM( val, writer );
    printf("%d is written\n", val );
}
cvEndWriteSeq( &writer );

cvStartReadSeq( seq, &reader, 0 );
for( i = 0; i &lt; seq->total; i++ )
{
    int val;
#if 1
    CV_READ_SEQ_ELEM( val, reader );
    printf("%d is read\n", val );
#else /* alternative way, that is prefferable if sequence elements are large,
         or their size/type is unknown at compile time */
    printf("%d is read\n", *(int*)reader.ptr );
    CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
#endif
}
...

cvReleaseStorage( &storage );
</pre>


<hr><h3><a name="decl_cvGetSeqReaderPos">GetSeqReaderPos</a></h3>
<p class="Blurb">Returns the current reader position</p>
<pre>
int cvGetSeqReaderPos( CvSeqReader* reader );
</pre><p><dl>
<dt>reader<dd>Reader state.
</dl><p>
The function <code>cvGetSeqReaderPos</code> returns the current reader position
(within 0 ... <code>reader->seq->total</code> - 1).</p>


<hr><h3><a name="decl_cvSetSeqReaderPos">SetSeqReaderPos</a></h3>
<p class="Blurb">Moves the reader to specified position</p>
<pre>
void cvSetSeqReaderPos( CvSeqReader* reader, int index, int is_relative=0 );
</pre><p><dl>

<dt>reader<dd>Reader state.
<dt>index<dd>The destination position. If the positioning mode is used (see the next parameter)
             the actual position will be <code>index</code> mod <code>reader->seq->total</code>.
<dt>is_relative<dd>If it is not zero, then <code>index</code> is a relative to the current position.
</dl><p>
The function <code>cvSetSeqReaderPos</code> moves the read position to the absolute position or
relative to the current position.
</p>


<hr><h2><a name="cxcore_ds_sets">Sets</a></h2>

<hr><h3><a name="decl_CvSet">CvSet</a></h3>
<p class="Blurb">Collection of nodes</p>
<pre>
    typedef struct CvSetElem
    {
        int flags; /* it is negative if the node is free and zero or positive otherwise */
        struct CvSetElem* next_free; /* if the node is free, the field is a
                                        pointer to next free node */
    }
    CvSetElem;

    #define CV_SET_FIELDS()    \
        CV_SEQUENCE_FIELDS()   /* inherits from <a href="#decl_CvSeq">CvSeq</a> */ \
        struct CvSetElem* free_elems; /* list of free nodes */

    typedef struct CvSet
    {
        CV_SET_FIELDS()
    } CvSet;
</pre>
<p>
The structure <a href="#decl_CvSet">CvSet</a> is a base for OpenCV sparse data structures.</p>
<p>As follows from the above declaration <a href="#decl_CvSet">CvSet</a> inherits from <a href="#decl_CvSeq">CvSeq</a>
and it adds <code>free_elems</code> field it to, which is a list of free nodes.
Every set node, whether free or not, is the element of the underlying sequence.
While there is no restrictions on elements of dense sequences, the set (and derived structures)
elements must start with integer field and be able to fit CvSetElem structure, because
these two fields (integer followed by the pointer) are required for organization of node set with
the list of free nodes. If a node is free, <code>flags</code> field is negative (the most-significant
bit, or MSB, of the field is set), and <code>next_free</code>
points to the next free node (the first free node is referenced by <code>free_elems</code> field of
<a href="#decl_CvSet">CvSet</a>). And if a node is occupied, <code>flags</code> field is positive and contains the node index
that may be retrieved using (set_elem->flags & CV_SET_ELEM_IDX_MASK) expression,
the rest of the node content is determined by the user. In particular, the occupied nodes
are not linked as the free nodes are, so the second field can be used for such a link as well as
for some different purpose. The macro <code>CV_IS_SET_ELEM(set_elem_ptr)</code>
can be used to determined whether the specified node is occupied or not.</p>
<p>
Initially the set and the list are empty. When a new node is requiested from the set,
it is taken from the list of free nodes, which is updated then. If the list appears to be empty,
a new sequence block is allocated and all the nodes within the block are joined in the list of free
nodes. Thus, <code>total</code> field of the set is the total number of nodes both occupied and free.
When an occupied node is released, it is added to the list of free nodes. The node released last
will be occupied first.</p>
<p>In OpenCV <a href="#decl_CvSet">CvSet</a> is used for representing graphs (<a href="#decl_CvGraph">CvGraph</a>),
sparse multi-dimensional arrays (<a href="#decl_CvSparseMat">CvSparseMat</a>), planar subdivisions (<a href="#decl_CvSubdiv2D">CvSubdiv2D</a>) etc.</p>


<hr><h3><a name="decl_cvCreateSet">CreateSet</a></h3>
<p class="Blurb">Creates empty set</p>
<pre>
CvSet* cvCreateSet( int set_flags, int header_size,
                    int elem_size, CvMemStorage* storage );
</pre><p><dl>
<dt>set_flags<dd>Type of the created set.
<dt>header_size<dd>Set header size; may not be less than <code>sizeof(CvSet)</code>.
<dt>elem_size<dd>Set element size; may not be less than <a href="#decl_CvSetElem">CvSetElem</a>.
<dt>storage<dd>Container for the set.
</dl><p>
The function <code>cvCreateSet</code> creates an empty set with a specified header size and element size, and
returns the pointer to the set. The function is just a thin layer on top of <a href="#decl_cvCreateSeq">cvCreateSeq</a>.</p>


<hr><h3><a name="decl_cvSetAdd">SetAdd</a></h3>
<p class="Blurb">Occupies a node in the set</p>
<pre>
int cvSetAdd( CvSet* set_header, CvSetElem* elem=NULL, CvSetElem** inserted_elem=NULL );
</pre><p><dl>
<dt>set_header<dd>Set.
<dt>elem<dd>Optional input argument, inserted element. If not NULL, the function
copies the data to the allocated node (The MSB of the first integer field is cleared after copying).
<dt>inserted_elem<dd>Optional output argument; the pointer to the allocated cell.
</dl><p>
The function <code>cvSetAdd</code> allocates a new node, optionally copies input element data
to it, and returns the pointer and the index to the node. The index value is
taken from the lower bits of <code>flags</code> field of the node. The function has O(1) complexity,
however there exists a faster function for allocating set nodes (see <a href="#decl_cvSetNew">cvSetNew</a>).
</p>


<hr><h3><a name="decl_cvSetRemove">SetRemove</a></h3>
<p class="Blurb">Removes element from set</p>
<pre>
void cvSetRemove( CvSet* set_header, int index );
</pre><p><dl>
<dt>set_header<dd>Set.
<dt>index<dd>Index of the removed element.
</dl><p>
The function <code>cvSetRemove</code> removes an element with a specified index from the set.
If the node at the specified location is not occupied the function does nothing.
The function has O(1) complexity, however, <a href="#decl_cvSetRemoveByPtr">cvSetRemoveByPtr</a> provides yet
faster way to remove a set element if it is located already.</p>


<hr><h3><a name="decl_cvSetNew">SetNew</a></h3>
<p class="Blurb">Adds element to set (fast variant)</p>
<pre>
CvSetElem* cvSetNew( CvSet* set_header );
</pre><p><dl>
<dt>set_header<dd>Set.
</dl><p>
The function <code>cvSetNew</code> is inline light-weight variant of <a href="#decl_cvSetAdd">cvSetAdd</a>.
It occupies a new node and returns pointer to it rather than index.</p>


<hr><h3><a name="decl_cvSetRemoveByPtr">SetRemoveByPtr</a></h3>
<p class="Blurb">Removes set element given its pointer</p>
<pre>
void cvSetRemoveByPtr( CvSet* set_header, void* elem );
</pre><p><dl>
<dt>set_header<dd>Set.
<dt>elem<dd>Removed element.
</dl><p>
The function <code>cvSetRemoveByPtr</code> is inline light-weight variant of <a href="#decl_cvSetRemove">cvSetRemove</a>
that takes element pointer.
The function does not check whether the node is occupied or not - the user should take care of it.</p>


<hr><h3><a name="decl_cvGetSetElem">GetSetElem</a></h3>
<p class="Blurb">Finds set element by its index</p>
<pre>
CvSetElem* cvGetSetElem( const CvSet* set_header, int index );
</pre><p><dl>
<dt>set_header<dd>Set.
<dt>index<dd>Index of the set element within a sequence.
</dl><p>
The function <code>cvGetSetElem</code> finds a set element by index. The function returns the
pointer to it or 0 if the index is invalid or the corresponding node is free.
The function supports negative indices as it uses <a href="#decl_cvGetSeqElem">cvGetSeqElem</a> to locate the node.</p>
</p>


<hr><h3><a name="decl_cvClearSet">ClearSet</a></h3>
<p class="Blurb">Clears set</p>
<pre>
void cvClearSet( CvSet* set_header );
</pre><p><dl>
<dt>set_header<dd>Cleared set.
</dl><p>
The function <code>cvClearSet</code> removes all elements from set. It has O(1) time complexity.</p>


<hr><h2><a name="cxcore_ds_graphs">Graphs</a></h2>

<hr><h3><a name="decl_CvGraph">CvGraph</a></h3>
<p class="Blurb">Oriented or unoriented weigted graph</p>
<pre>
    #define CV_GRAPH_VERTEX_FIELDS()    \
        int flags; /* vertex flags */   \
        struct CvGraphEdge* first; /* the first incident edge */

    typedef struct CvGraphVtx
    {
        CV_GRAPH_VERTEX_FIELDS()
    }
    CvGraphVtx;

    #define CV_GRAPH_EDGE_FIELDS()      \
        int flags; /* edge flags */     \
        float weight; /* edge weight */ \
        struct CvGraphEdge* next[2]; /* the next edges in the incidence lists for staring (0) */ \
                                     /* and ending (1) vertices */ \
        struct CvGraphVtx* vtx[2]; /* the starting (0) and ending (1) vertices */

    typedef struct CvGraphEdge
    {
        CV_GRAPH_EDGE_FIELDS()
    }
    CvGraphEdge;

    #define  CV_GRAPH_FIELDS()                  \
        CV_SET_FIELDS() /* set of vertices */   \
        CvSet* edges;   /* set of edges */

    typedef struct CvGraph
    {
        CV_GRAPH_FIELDS()
    }
    CvGraph;

</pre>
<p>
The structure <a href="#decl_CvGraph">CvGraph</a> is a base for graphs used in OpenCV.</p>
<p>Graph structure inherits from <a href="#decl_CvSet">CvSet</a> - this part describes common graph properties and
the graph vertices, and contains another set as a member - this part describes the graph edges.</p>
<p>The vertex, edge and the graph header structures are declared using the same technique as other
extendible OpenCV structures - via macros, that simplifies extension and customization of the structures.
While the vertex and edge structures do not inherit from <a href="#decl_CvSetElem">CvSetElem</a> explicitly, they satisfy
both conditions on the set elements - have an integer field in the beginning and fit CvSetElem structure.
The <code>flags</code> fields are used as for indicating occupied vertices and edges as well as
for other purposes, for example, for graph traversal (see <a href="#decl_cvCreateGraphScanner">cvCreateGraphScanner</a> et al.), so
it is better not to use them directly.</p>
<p>The graph is represented as a set of edges each of whose has the list of incident edges. The incidence
lists for different vertices are interleaved to avoid information duplication as much as posssible.</p>
<p>The graph may be oriented or unoriented. In the latter case there is no distiction between edge
connecting vertex A with vertex B and the edge connecting vertex B with vertex A - only one of them
can exist in the graph at the same moment and it represents both &lt;A, B&gt; and &lt;B, A&gt; edges..</p>



<hr><h3><a name="decl_cvCreateGraph">CreateGraph</a></h3>
<p class="Blurb">Creates empty graph</p>
<pre>
CvGraph* cvCreateGraph( int graph_flags, int header_size, int vtx_size,
                        int edge_size, CvMemStorage* storage );
</pre><p><dl>
<dt>graph_flags<dd>Type of the created graph. Usually, it is either <code>CV_SEQ_KIND_GRAPH</code>
for generic unoriented graphs and <code>CV_SEQ_KIND_GRAPH | CV_GRAPH_FLAG_ORIENTED</code> for generic oriented graphs.
<dt>header_size<dd>Graph header size; may not be less than <code>sizeof(CvGraph).</code>
<dt>vtx_size<dd>Graph vertex size; the custom vertex structure must start with <a href="#decl_CvGraphVtx">CvGraphVtx</a>
                  (use <code>CV_GRAPH_VERTEX_FIELDS()</code>)
<dt>edge_size<dd>Graph edge size; the custom edge structure must start with <a href="#decl_CvGraphEdge">CvGraphEdge</a>
                (use <code>CV_GRAPH_EDGE_FIELDS()</code>)
<dt>storage<dd>The graph container.
</dl><p>
The function <code>cvCreateGraph</code> creates an empty graph and returns pointer to it.</p>


<hr><h3><a name="decl_cvGraphAddVtx">GraphAddVtx</a></h3>
<p class="Blurb">Adds vertex to graph</p>
<pre>
int cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* vtx=NULL,
                   CvGraphVtx** inserted_vtx=NULL );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>vtx<dd>Optional input argument used to initialize the added vertex (only user-defined fields
beyond <code>sizeof(CvGraphVtx)</code> are copied).
<dt>inserted_vertex<dd>Optional output argument. If not <code>NULL</code>, the address of the new
vertex is written there.
</dl><p>
The function <code>cvGraphAddVtx</code> adds a vertex to the graph and returns the vertex
index.</p>


<hr><h3><a name="decl_cvGraphRemoveVtx">GraphRemoveVtx</a></h3>
<p class="Blurb">Removes vertex from graph</p>
<pre>
int cvGraphRemoveVtx( CvGraph* graph, int index );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>vtx_idx<dd>Index of the removed vertex.
</dl><p>
The function <code>cvGraphRemoveAddVtx</code> removes a vertex from the graph together with all
the edges incident to it. The function reports an error, if the input vertex does
not belong to the graph. The return value is number of edges deleted,
or -1 if the vertex does not belong to the graph.</p>


<hr><h3><a name="decl_cvGraphRemoveVtxByPtr">GraphRemoveVtxByPtr</a></h3>
<p class="Blurb">Removes vertex from graph</p>
<pre>
int cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>vtx<dd>Pointer to the removed vertex.
</dl><p>
The function <code>cvGraphRemoveVtxByPtr</code> removes a vertex from the graph together with
all the edges incident to it. The function reports an error, if the vertex does not belong to the graph.
The return value is number of edges deleted, or -1 if the vertex does not belong to the graph.</p>


<hr><h3><a name="decl_cvGetGraphVtx">GetGraphVtx</a></h3>
<p class="Blurb">Finds graph vertex by index</p>
<pre>
CvGraphVtx* cvGetGraphVtx( CvGraph* graph, int vtx_idx );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>vtx_idx<dd>Index of the vertex.
</dl><p>
The function <code>cvGetGraphVtx</code> finds the graph vertex by index and returns the pointer
to it or NULL if the vertex does not belong to the graph.</p>


<hr><h3><a name="decl_cvGraphVtxIdx">GraphVtxIdx</a></h3>
<p class="Blurb">Returns index of graph vertex</p>
<pre>
int cvGraphVtxIdx( CvGraph* graph, CvGraphVtx* vtx );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>vtx<dd>Pointer to the graph vertex.
</dl><p>
The function <code>cvGraphVtxIdx</code> returns index of the graph vertex.</p>


<hr><h3><a name="decl_cvGraphAddEdge">GraphAddEdge</a></h3>
<p class="Blurb">Adds edge to graph</p>
<pre>
int cvGraphAddEdge( CvGraph* graph, int start_idx, int end_idx,
                    const CvGraphEdge* edge=NULL, CvGraphEdge** inserted_edge=NULL );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>start_idx<dd>Index of the starting vertex of the edge.
<dt>end_idx<dd>Index of the ending vertex of the edge. For unoriented graph the order of the vertex
parameters does not matter.
<dt>edge<dd>Optional input parameter, initialization data for the edge.
<dt>inserted_edge<dd>Optional output parameter to contain the address of the inserted
edge.
</dl><p>
The function <code>cvGraphAddEdge</code> connects two specified vertices.
The function returns 1 if the edge has been added successfully, 0 if the edge connecting
the two vertices exists already and -1 if either of the vertices was not found, the starting and
the ending vertex are the same or there is some other critical situation. In the latter case
(i.e. when the result is negative) the function also reports an error by default.</p>


<hr><h3><a name="decl_cvGraphAddEdgeByPtr">GraphAddEdgeByPtr</a></h3>
<p class="Blurb">Adds edge to graph</p>
<pre>
int cvGraphAddEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, CvGraphVtx* end_vtx,
                         const CvGraphEdge* edge=NULL, CvGraphEdge** inserted_edge=NULL );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>start_vtx<dd>Pointer to the starting vertex of the edge.
<dt>end_vtx<dd>Pointer to the ending vertex of the edge. For unoriented graph the order of the vertex
parameters does not matter.
<dt>edge<dd>Optional input parameter, initialization data for the edge.
<dt>inserted_edge<dd>Optional output parameter to contain the address of the inserted
edge within the edge set.
</dl><p>
The function <code>cvGraphAddEdge</code> connects two specified vertices.
The function returns 1 if the edge has been added successfully, 0 if the edge connecting
the two vertices exists already and -1 if either of the vertices was not found, the starting and
the ending vertex are the same or there is some other critical situation. In the latter case
(i.e. when the result is negative) the function also reports an error by default.</p>


<hr><h3><a name="decl_cvGraphRemoveEdge">GraphRemoveEdge</a></h3>
<p class="Blurb">Removes edge from graph</p>
<pre>
void cvGraphRemoveEdge( CvGraph* graph, int start_idx, int end_idx );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>start_idx<dd>Index of the starting vertex of the edge.
<dt>end_idx<dd>Index of the ending vertex of the edge. For unoriented graph the order of the vertex
parameters does not matter.
</dl><p>
The function <code>cvGraphRemoveEdge</code> removes the edge connecting two specified vertices.
If the vertices are not connected [in that order], the function does nothing.
</p>


<hr><h3><a name="decl_cvGraphRemoveEdgeByPtr">GraphRemoveEdgeByPtr</a></h3>
<p class="Blurb">Removes edge from graph</p>
<pre>
void cvGraphRemoveEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, CvGraphVtx* end_vtx );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>start_vtx<dd>Pointer to the starting vertex of the edge.
<dt>end_vtx<dd>Pointer to the ending vertex of the edge. For unoriented graph the order of the vertex
parameters does not matter.
</dl><p>
The function <code>cvGraphRemoveEdgeByPtr</code> removes the edge connecting two specified vertices.
If the vertices are not connected [in that order], the function does nothing.</p>


<hr><h3><a name="decl_cvFindGraphEdge">FindGraphEdge</a></h3>
<p class="Blurb">Finds edge in graph</p>
<pre>
CvGraphEdge* cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx );
#define cvGraphFindEdge cvFindGraphEdge
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>start_idx<dd>Index of the starting vertex of the edge.
<dt>end_idx<dd>Index of the ending vertex of the edge. For unoriented graph the order of the vertex
parameters does not matter.
</dl><p>
The function <code>cvFindGraphEdge</code> finds the graph edge connecting two specified vertices
and returns pointer to it or NULL if the edge does not exists.</p>


<hr><h3><a name="decl_cvFindGraphEdgeByPtr">FindGraphEdgeByPtr</a></h3>
<p class="Blurb">Finds edge in graph</p>
<pre>
CvGraphEdge* cvFindGraphEdgeByPtr( const CvGraph* graph, const CvGraphVtx* start_vtx,
                                   const CvGraphVtx* end_vtx );
#define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>start_vtx<dd>Pointer to the starting vertex of the edge.
<dt>end_vtx<dd>Pointer to the ending vertex of the edge. For unoriented graph the order of the vertex
parameters does not matter.
</dl><p>
The function <code>cvFindGraphEdge</code> finds the graph edge connecting two specified vertices
and returns pointer to it or NULL if the edge does not exists.</p>


<hr><h3><a name="decl_cvGraphEdgeIdx">GraphEdgeIdx</a></h3>
<p class="Blurb">Returns index of graph edge</p>
<pre>
int cvGraphEdgeIdx( CvGraph* graph, CvGraphEdge* edge );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>edge<dd>Pointer to the graph edge.
</dl><p>
The function <code>cvGraphEdgeIdx</code> returns index of the graph edge.</p>


<hr><h3><a name="decl_cvGraphVtxDegree">GraphVtxDegree</a></h3>
<p class="Blurb">Counts edges indicent to the vertex</p>
<pre>
int cvGraphVtxDegree( const CvGraph* graph, int vtx_idx );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>vtx<dd>Index of the graph vertex.
</dl><p>
The function <code>cvGraphVtxDegree</code> returns the number of edges
incident to the specified vertex, both incoming and outcoming.
To count the edges, the following code is used:</p>
<pre>
    CvGraphEdge* edge = vertex->first; int count = 0;
    while( edge )
    {
        edge = CV_NEXT_GRAPH_EDGE( edge, vertex );
        count++;
    }
</pre>
<p>The macro <code>CV_NEXT_GRAPH_EDGE( edge, vertex )</code> returns the edge incident to <code>vertex</code>
that follows after <code>edge</code>.</p>


<hr><h3><a name="decl_cvGraphVtxDegreeByPtr">GraphVtxDegreeByPtr</a></h3>
<p class="Blurb">Finds edge in graph</p>
<pre>
int cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vtx );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>vtx<dd>Pointer to the graph vertex.
</dl><p>
The function <code>cvGraphVtxDegree</code> returns the number of edges
incident to the specified vertex, both incoming and outcoming.</p>


<hr><h3><a name="decl_cvClearGraph">ClearGraph</a></h3>
<p class="Blurb">Clears graph</p>
<pre>
void cvClearGraph( CvGraph* graph );
</pre><p><dl>
<dt>graph<dd>Graph.
</dl><p>
The function <code>cvClearGraph</code> removes all vertices and edges from the graph.
The function has O(1) time complexity.</p>


<hr><h3><a name="decl_cvCloneGraph">CloneGraph</a></h3>
<p class="Blurb">Clone graph</p>
<pre>
CvGraph* cvCloneGraph( const CvGraph* graph, CvMemStorage* storage );
</pre><p><dl>
<dt>graph<dd>The graph to copy.
<dt>storage<dd>Container for the copy.
</dl><p>
The function <code>cvCloneGraph</code> creates full copy of the graph. If the graph vertices
or edges have pointers to some external data, it still be shared between the copies.
The vertex and edge indices in the new graph may be different from the original, because
the function defragments the vertex and edge sets.</p>


<hr><h3><a name="decl_CvGraphScanner">CvGraphScanner</a></h3>
<p class="Blurb">Graph traversal state</p>
<pre>
    typedef struct CvGraphScanner
    {
        CvGraphVtx* vtx;       /* current graph vertex (or current edge origin) */
        CvGraphVtx* dst;       /* current graph edge destination vertex */
        CvGraphEdge* edge;     /* current edge */

        CvGraph* graph;        /* the graph */
        CvSeq*   stack;        /* the graph vertex stack */
        int      index;        /* the lower bound of certainly visited vertices */
        int      mask;         /* event mask */
    }
    CvGraphScanner;
</pre>
<p>The structure <a href="#decl_CvGraphScanner">CvGraphScanner</a> is used for depth-first graph traversal.
See discussion of the functions below.</p>


<hr><h3><a name="decl_cvCreateGraphScanner">CreateGraphScanner</a></h3>
<p class="Blurb">Creates structure for depth-first graph traversal</p>
<pre>
CvGraphScanner*  cvCreateGraphScanner( CvGraph* graph, CvGraphVtx* vtx=NULL,
                                       int mask=CV_GRAPH_ALL_ITEMS );
</pre><p><dl>
<dt>graph<dd>Graph.
<dt>vtx<dd>Initial vertex to start from. If NULL, the traversal starts from the first vertex (a vertex with the
           minimal index in the sequence of vertices).
<dt>mask<dd>Event mask indicating which events are interesting to the user (where <a href="#decl_cvNextGraphItem">cvNextGraphItem</a>
            function returns control to the user)
            It can be <code>CV_GRAPH_ALL_ITEMS</code> (all events are interesting)
            or combination of the following flags:<ul>
            <li>CV_GRAPH_VERTEX - stop at the graph vertices visited for the first time<br>
            <li>CV_GRAPH_TREE_EDGE - stop at tree edges (<code>tree edge</code> is the edge connecting the last visited vertex and
                                 the vertex to be visited next)<br>
            <li>CV_GRAPH_BACK_EDGE - stop at back edges (<code>back edge</code> is an edge connecting
                                 the last visited vertex with some of its ancestors in the search tree)<br>
            <li>CV_GRAPH_FORWARD_EDGE - stop at forward edges (<code>forward edge</code> is an edge conecting
                                 the last visited vertex with some of its descendants in the search tree).
                                 The <code>forward edges</code> are only possible during oriented graph traversal)<br>
            <li>CV_GRAPH_CROSS_EDGE - stop at cross edges (<code>cross edge</code> is an edge connecting different search trees or
                                 branches of the same tree.
                                 The <code>cross edges</code> are only possible during oriented graphs traversal)<br>
            <li>CV_GRAPH_ANY_EDGE - stop and any edge (<code>tree, back, forward</code> and <code>cross edges</code>)<br>
            <li>CV_GRAPH_NEW_TREE - stop in the beginning of every new search tree. When the traversal procedure
                                visits all vertices and edges reachible from the initial vertex (the visited vertices
                                together with tree edges make up a tree), it searches for some unvisited vertex
                                in the graph and resumes the traversal process from that vertex.
                                Before starting a new tree (including the very first tree
                                when <code>cvNextGraphItem</code> is called for the first time)
                                it generates <code>CV_GRAPH_NEW_TREE</code> event.<br>
                                For unoriented graphs each search tree corresponds to a connected component of the graph.<br>
            <li>CV_GRAPH_BACKTRACKING - stop at every already visited vertex during backtracking - returning to
                                already visited vertexes of the traversal tree.<br></ul>
</dl><p>
The function <code>cvCreateGraphScanner</code> creates structure for
depth-first graph traversal/search.
The initialized structure is used in <a href="#decl_cvNextGraphItem">cvNextGraphItem</a> function
- the incremental traversal procedure.</p>


<hr><h3><a name="decl_cvNextGraphItem">NextGraphItem</a></h3>
<p class="Blurb">Makes one or more steps of the graph traversal procedure</p>
<pre>
int cvNextGraphItem( CvGraphScanner* scanner );
</pre><p><dl>
<dt>scanner<dd>Graph traversal state. It is updated by the function.
</dl><p>
The function <code>cvNextGraphItem</code> traverses through the graph until an event interesting to the user
(that is, an event, specified in the <code>mask</code> in <a href="#decl_cvCreateGraphScanner">cvCreateGraphScanner</a> call)
is met or the traversal is over. In the first case it returns one of the events,
listed in the description of <code>mask</code> parameter above and with the next call
it resumes the traversal. In the latter case it returns CV_GRAPH_OVER (-1).
When the event is <code>CV_GRAPH_VERTEX</code>, or <code>CV_GRAPH_BACKTRACKING</code> or <code>CV_GRAPH_NEW_TREE</code>,
the currently observed vertex is stored in <code>scanner->vtx</code>. And if the event is edge-related,
the edge itself is stored at <code>scanner->edge</code>,
the previously visited vertex - at <code>scanner->vtx</code> and the other ending vertex of the edge -
at <code>scanner->dst</code>.</p>


<hr><h3><a name="decl_cvReleaseGraphScanner">ReleaseGraphScanner</a></h3>
<p class="Blurb">Finishes graph traversal procedure</p>
<pre>
void cvReleaseGraphScanner( CvGraphScanner** scanner );
</pre><p><dl>
<dt>scanner<dd>Double pointer to graph traverser.
</dl><p>
The function <code>cvGraphScanner</code> finishes graph traversal procedure
and releases the traverser state.</p>


<hr><h2><a name="cxcore_ds_trees">Trees</a></h2>


<hr><h3><a name="decl_CV_TREE_NODE_FIELDS">CV_TREE_NODE_FIELDS</a></h3>
<p class="Blurb">Helper macro for a tree node type declaration</p>
<pre>
#define CV_TREE_NODE_FIELDS(node_type)                          \
    int       flags;         /* micsellaneous flags */          \
    int       header_size;   /* size of sequence header */      \
    struct    node_type* h_prev; /* previous sequence */        \
    struct    node_type* h_next; /* next sequence */            \
    struct    node_type* v_prev; /* 2nd previous sequence */    \
    struct    node_type* v_next; /* 2nd next sequence */
</pre>
<p>The macro <code>CV_TREE_NODE_FIELDS()</code> is used to declare structures
that can be organized into hierarchical strucutures (trees), such as <a href="#decl_CvSeq">CvSeq</a> -
the basic type for all dynamical structures.
The trees made of nodes declared using this macro can be processed using
the functions described below in this section.</p>


<hr><h3><a name="decl_CvTreeNodeIterator">CvTreeNodeIterator</a></h3>
<p class="Blurb">Opens existing or creates new file storage</p>
<pre>
typedef struct CvTreeNodeIterator
{
    const void* node;
    int level;
    int max_level;
}
CvTreeNodeIterator;
</pre>
<p>The structure <a href="#decl_CvTreeNodeIterator">CvTreeNodeIterator</a> is used to traverse trees.
The tree node declaration should start with <code>CV_TREE_NODE_FIELDS(...)</code> macro.</p>


<hr><h3><a name="decl_cvInitTreeNodeIterator">InitTreeNodeIterator</a></h3>
<p class="Blurb">Initializes tree node iterator</p>
<pre>
void cvInitTreeNodeIterator( CvTreeNodeIterator* tree_iterator,
                             const void* first, int max_level );
</pre><p><dl>
<dt>tree_iterator<dd>Tree iterator initialized by the function.
<dt>first<dd>The initial node to start traversing from.
<dt>max_level<dd>The maximal level of the tree (<code>first</code> node assumed to be at the first level) to
                traverse up to. For example, 1 means that only nodes at the same level as <code>first</code>
                should be visited, 2 means that the nodes on the same level as <code>first</code> and
                their direct children should be visited etc.
</dl><p>
The function <code>cvInitTreeNodeIterator</code> initializes tree iterator.
The tree is traversed in depth-first order.</p>


<hr><h3><a name="decl_cvNextTreeNode">NextTreeNode</a></h3>
<p class="Blurb">Returns the currently observed node and moves iterator toward the next node</p>
<pre>
void* cvNextTreeNode( CvTreeNodeIterator* tree_iterator );
</pre><p><dl>
<dt>tree_iterator<dd>Tree iterator initialized by the function.
</dl><p>
The function <code>cvNextTreeNode</code> returns the currently observed node and then
updates the iterator - moves it toward the next node. In other words, the function behavior
is similar to *p++ expression on usual C pointer or C++ collection iterator.
The function returns NULL if there is no more nodes.</p>


<hr><h3><a name="decl_cvPrevTreeNode">PrevTreeNode</a></h3>
<p class="Blurb">Returns the currently observed node and moves iterator toward the previous node</p>
<pre>
void* cvPrevTreeNode( CvTreeNodeIterator* tree_iterator );
</pre><p><dl>
<dt>tree_iterator<dd>Tree iterator initialized by the function.
</dl><p>
The function <code>cvPrevTreeNode</code> returns the currently observed node and then
updates the iterator - moves it toward the previous node. In other words, the function behavior
is similar to *p-- expression on usual C pointer or C++ collection iterator.
The function returns NULL if there is no more nodes.</p>


<hr><h3><a name="decl_cvTreeToNodeSeq">TreeToNodeSeq</a></h3>
<p class="Blurb">Gathers all node pointers to the single sequence</p>
<pre>
CvSeq* cvTreeToNodeSeq( const void* first, int header_size, CvMemStorage* storage );
</pre><p><dl>
<dt>first<dd>The initial tree node.
<dt>header_size<dd>Header size of the created sequence (sizeof(CvSeq) is the most used value).
<dt>storage<dd>Container for the sequence.
</dl><p>
The function <code>cvTreeToNodeSeq</code> puts pointers of all nodes reacheable from <code>first</code>
to the single sequence. The pointers are written subsequently in the depth-first order.</p>


<hr><h3><a name="decl_cvInsertNodeIntoTree">InsertNodeIntoTree</a></h3>
<p class="Blurb">Adds new node to the tree</p>
<pre>
void cvInsertNodeIntoTree( void* node, void* parent, void* frame );
</pre><p><dl>
<dt>node<dd>The inserted node.
<dt>parent<dd>The parent node that is already in the tree.
<dt>frame<dd>The top level node. If <code>parent</code> and <code>frame</code> are the same, <code>v_prev</code>
            field of <code>node</code> is set to NULL rather than <code>parent</code>.
</dl><p>
The function <code>cvInsertNodeIntoTree</code> adds another node into tree. The function does not
allocate any memory, it can only modify links of the tree nodes.</p>


<hr><h3><a name="decl_cvRemoveNodeFromTree">RemoveNodeFromTree</a></h3>
<p class="Blurb">Removes node from tree</p>
<pre>
void cvRemoveNodeFromTree( void* node, void* frame );
</pre><p><dl>
<dt>node<dd>The removed node.
<dt>frame<dd>The top level node. If <code>node->v_prev = NULL</code> and
            <code>node->h_prev</code> is NULL (i.e. if <code>node</code> is the first child of <code>frame</code>),
            <code>frame->v_next</code> is set to <code>node->h_next</code> (i.e. the first child or frame is changed).
</dl><p>
The function <code>cvRemoveNodeFromTree</code> removes node from tree. The function does not
deallocate any memory, it can only modify links of the tree nodes.</p>



<hr><h1><a name="cxcore_drawing">Drawing Functions</a></h1>

<p>
Drawing functions work with matrices/images or arbitrary depth.
Antialiasing is implemented only for 8-bit images.
All the functions include parameter color that means rgb value (that may be
constructed with <code>CV_RGB</code> macro or <code>cvScalar</code> function)
for color images and brightness for grayscale images.</p><p>
If a drawn figure is partially or completely outside the image, it is clipped.
For color images the order channel is: <font color=blue>B</font>lue <font color=green>G</font>reen <font color=red>R</font>ed ... 
If one needs a different channel order, it is possible to construct color
via <code>cvScalar</code> with the particular channel order, or
convert the image before and/or after drawing in it with
<a href="opencvref_cv.htm#decl_cvCvtColor">cvCvtColor</a> or
<a href="#decl_cvTransform">cvTransform</a>.
</p>


<hr><h2><a name="cxcore_drawing_shapes">Curves and Shapes</a></h2>

<hr><h3><a name="decl_CV_RGB">CV_RGB</a></h3>
<p class="Blurb">Constructs a color value</p>
<pre>
#define CV_RGB( r, g, b )  cvScalar( (b), (g), (r) )
</pre>


<hr><h3><a name="decl_cvLine">Line</a></h3>
<p class="Blurb">Draws a line segment connecting two points</p>
<pre>
void cvLine( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color,
             int thickness=1, int line_type=8, int shift=0 );
</pre><p><dl>
<dt>img<dd>The image.
<dt>pt1<dd>First point of the line segment.
<dt>pt2<dd>Second point of the line segment.
<dt>color<dd>Line color.
<dt>thickness<dd>Line thickness.
<dt>line_type<dd>Type of the line:<br>
                 <code>8</code> (or <code>0</code>) - 8-connected line.<br>
                 <code>4</code> - 4-connected line.<br>
                 <code>CV_AA</code> - antialiased line.
<dt>shift<dd>Number of fractional bits in the point coordinates.
</dl><p>
The function <code>cvLine</code> draws the line segment between <code>pt1</code> and <code>pt2</code> points
in the image. The line is clipped by the image or ROI rectangle. For non-antialiased lines
with integer coordinates the 8-connected or 4-connected Bresenham algorithm is used.
Thick lines are drawn with rounding endings. Antialiased lines are drawn using Gaussian filtering.
To specify the line color, the user may use the macro <code>CV_RGB( r, g, b )</code>.</p>


<hr><h3><a name="decl_cvRectangle">Rectangle</a></h3>
<p class="Blurb">Draws simple, thick or filled rectangle</p>
<pre>
void cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color,
                  int thickness=1, int line_type=8, int shift=0 );
</pre><p><dl>
<dt>img<dd>Image.
<dt>pt1<dd>One of the rectangle vertices.
<dt>pt2<dd>Opposite rectangle vertex.
<dt>color<dd>Line color (RGB) or brightness (grayscale image).
<dt>thickness<dd>Thickness of lines that make up the rectangle. Negative values, e.g. CV_FILLED,
make the function to draw a filled rectangle.
<dt>line_type<dd>Type of the line, see <a href="#decl_cvLine">cvLine</a> description.
<dt>shift<dd>Number of fractional bits in the point coordinates.
</dl><p>
The function <code>cvRectangle</code> draws a rectangle with
two opposite corners <code>pt1</code> and <code>pt2</code>.</p>


<hr><h3><a name="decl_cvCircle">Circle</a></h3>
<p class="Blurb">Draws a circle</p>
<pre>
void cvCircle( CvArr* img, CvPoint center, int radius, CvScalar color,
               int thickness=1, int line_type=8, int shift=0 );
</pre><p><dl>
<dt>img<dd>Image where the circle is drawn.
<dt>center<dd>Center of the circle.
<dt>radius<dd>Radius of the circle.
<dt>color<dd>Circle color.
<dt>thickness<dd>Thickness of the circle outline if positive, otherwise indicates that
a filled circle has to be drawn.
<dt>line_type<dd>Type of the circle boundary, see <a href="#decl_cvLine">cvLine</a> description.
<dt>shift<dd>Number of fractional bits in the center coordinates and radius value.
</dl><p>
The function <code>cvCircle</code> draws a simple or filled circle with given center and
radius. The circle is clipped by ROI rectangle. To specify the circle color, the user may
use the macro <code>CV_RGB ( r, g, b )</code>.</p>


<hr><h3><a name="decl_cvEllipse">Ellipse</a></h3>
<p class="Blurb">Draws simple or thick elliptic arc or fills ellipse sector</p>
<pre>
void cvEllipse( CvArr* img, CvPoint center, CvSize axes, double angle,
                double start_angle, double end_angle, CvScalar color,
                int thickness=1, int line_type=8, int shift=0 );
</pre><p><dl>
<dt>img<dd>Image.
<dt>center<dd>Center of the ellipse.
<dt>axes<dd>Length of the ellipse axes.
<dt>angle<dd>Rotation angle.
<dt>start_angle<dd>Starting angle of the elliptic arc.
<dt>end_angle<dd>Ending angle of the elliptic arc.
<dt>color<dd>Ellipse color.
<dt>thickness<dd>Thickness of the ellipse arc.
<dt>line_type<dd>Type of the ellipse boundary, see <a href="#decl_cvLine">cvLine</a> description.
<dt>shift<dd>Number of fractional bits in the center coordinates and axes' values.
</dl><p>
The function <code>cvEllipse</code> draws a simple or thick elliptic arc or fills an ellipse
sector. The arc is clipped by ROI rectangle. A piecewise-linear
approximation is used for antialiased arcs and thick arcs. All the angles are
given in degrees. The picture below explains the meaning of the parameters.</p>
<p>
<font color=blue>Parameters of Elliptic Arc</font>
</p>
<p>
<img align="center" src="pics/ellipse.png" >
</p>


<hr><h3><a name="decl_cvEllipseBox">EllipseBox</a></h3>
<p class="Blurb">Draws simple or thick elliptic arc or fills ellipse sector</p>
<pre>
void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color,
                   int thickness=1, int line_type=8, int shift=0 );
</pre><p><dl>
<dt>img<dd>Image.
<dt>box<dd>The enclosing box of the ellipse drawn
<dt>thickness<dd>Thickness of the ellipse boundary.
<dt>line_type<dd>Type of the ellipse boundary, see <a href="#decl_cvLine">cvLine</a> description.
<dt>shift<dd>Number of fractional bits in the box vertex coordinates.
</dl><p>
The function <code>cvEllipseBox</code> draws a simple or thick ellipse outline,
or fills an ellipse. The functions provides a convenient way to draw an ellipse
approximating some shape; that is what <a href="opencvref_cv.htm#decl_cvCamShift">cvCamShift</a>
and <a href="opencvref_cv.htm#decl_cvFitEllipse">cvFitEllipse</a> do.
The ellipse drawn is clipped by ROI rectangle. A piecewise-linear
approximation is used for antialiased arcs and thick arcs.</p>


<hr><h3><a name="decl_cvFillPoly">FillPoly</a></h3>
<p class="Blurb">Fills polygons interior</p>
<pre>
void cvFillPoly( CvArr* img, CvPoint** pts, int* npts, int contours,
                 CvScalar color, int line_type=8, int shift=0 );
</pre><p><dl>
<dt>img<dd>Image.
<dt>pts<dd>Array of pointers to polygons.
<dt>npts<dd>Array of polygon vertex counters.
<dt>contours<dd>Number of contours that bind the filled region.
<dt>color<dd>Polygon color.
<dt>line_type<dd>Type of the polygon boundaries, see <a href="#decl_cvLine">cvLine</a> description.
<dt>shift<dd>Number of fractional bits in the vertex coordinates.
</dl><p>
The function <code>cvFillPoly</code> fills an area bounded by several polygonal contours.
The function fills complex areas, for example, areas with holes, contour self-intersection, etc.</p>


<hr><h3><a name="decl_cvFillConvexPoly">FillConvexPoly</a></h3>
<p class="Blurb">Fills convex polygon</p>
<pre>
void cvFillConvexPoly( CvArr* img, CvPoint* pts, int npts,
                       CvScalar color, int line_type=8, int shift=0 );
</pre><p><dl>
<dt>img<dd>Image.
<dt>pts<dd>Array of pointers to a single polygon.
<dt>npts<dd>Polygon vertex counter.
<dt>color<dd>Polygon color.
<dt>line_type<dd>Type of the polygon boundaries, see <a href="#decl_cvLine">cvLine</a> description.
<dt>shift<dd>Number of fractional bits in the vertex coordinates.
</dl><p>
The function <code>cvFillConvexPoly</code> fills convex polygon interior.
This function is much faster than The function <code>cvFillPoly</code> and can fill
not only the convex polygons but any monotonic polygon, i.e. a polygon whose contour intersects every
horizontal line (scan line) twice at the most.</p>


<hr><h3><a name="decl_cvPolyLine">PolyLine</a></h3>
<p class="Blurb">Draws simple or thick polygons</p>
<pre>
void cvPolyLine( CvArr* img, CvPoint** pts, int* npts, int contours, int is_closed,
                 CvScalar color, int thickness=1, int line_type=8, int shift=0 );
</pre><p><dl>
<dt>img<dd>Image.
<dt>pts<dd>Array of pointers to polylines.
<dt>npts<dd>Array of polyline vertex counters.
<dt>contours<dd>Number of polyline contours.
<dt>is_closed<dd>Indicates whether the polylines must be drawn closed. If closed, the
function draws the line from the last vertex of every contour to the first
vertex.
<dt>color<dd>Polyline color.
<dt>thickness<dd>Thickness of the polyline edges.
<dt>line_type<dd>Type of the line segments, see <a href="#decl_cvLine">cvLine</a> description.
<dt>shift<dd>Number of fractional bits in the vertex coordinates.
</dl><p>
The function <code>cvPolyLine</code> draws a single or multiple polygonal curves.</p>


<hr><h2><a name="cxcore_drawing_text">Text</a></h2>

<hr><h3><a name="decl_cvInitFont">InitFont</a></h3>
<p class="Blurb">Initializes font structure</p>
<pre>
void cvInitFont( CvFont* font, int font_face, double hscale,
                 double vscale, double shear=0,
                 int thickness=1, int line_type=8 );
</pre><p><dl>
<dt>font<dd>Pointer to the font structure initialized by the function.
<dt>font_face<dd>Font name identifier. Only a subset of Hershey fonts
(<a href="http://sources.isc.org/utils/misc/hershey-font.txt">http://sources.isc.org/utils/misc/hershey-font.txt</a>)
are supported now:<br>
    <code>CV_FONT_HERSHEY_SIMPLEX</code> - normal size sans-serif font<br>
    <code>CV_FONT_HERSHEY_PLAIN</code> - small size sans-serif font<br>
    <code>CV_FONT_HERSHEY_DUPLEX</code> - normal size sans-serif font (more complex than <code>CV_FONT_HERSHEY_SIMPLEX</code>)<br>
    <code>CV_FONT_HERSHEY_COMPLEX</code> - normal size serif font<br>
    <code>CV_FONT_HERSHEY_TRIPLEX</code> - normal size serif font (more complex than <code>CV_FONT_HERSHEY_COMPLEX</code>)<br>
    <code>CV_FONT_HERSHEY_COMPLEX_SMALL</code> - smaller version of <code>CV_FONT_HERSHEY_COMPLEX</code><br>
    <code>CV_FONT_HERSHEY_SCRIPT_SIMPLEX</code> - hand-writing style font<br>
    <code>CV_FONT_HERSHEY_SCRIPT_COMPLEX</code> - more complex variant of <code>CV_FONT_HERSHEY_SCRIPT_SIMPLEX</code><br>
    The parameter can be composited from one of the values above and optional <code>CV_FONT_ITALIC</code> flag,
    that means italic or oblique font.
<dt>hscale<dd>Horizontal scale. If equal to <code>1.0f</code>, the characters have the original
width depending on the font type. If equal to <code>0.5f</code>, the characters are of half
the original width.
<dt>vscale<dd>Vertical scale. If equal to <code>1.0f</code>, the characters have the original
height depending on the font type. If equal to <code>0.5f</code>, the characters are of half
the original height.
<dt>shear<dd>Approximate tangent of the character slope relative to the vertical
line. Zero value means a non-italic font, <code>1.0f</code> means <code>&asymp;45&deg;</code> slope, etc.
thickness Thickness of lines composing letters outlines. The function <code>cvLine</code> is
used for drawing letters.
<dt>thickness<dd>Thickness of the text strokes.
<dt>line_type<dd>Type of the strokes, see <a href="#decl_cvLine">cvLine</a> description.
</dl><p>
The function <code>cvInitFont</code> initializes the font structure that can be passed to
text rendering functions.</p>


<hr><h3><a name="decl_cvPutText">PutText</a></h3>
<p class="Blurb">Draws text string</p>
<pre>
void cvPutText( CvArr* img, const char* text, CvPoint org, const CvFont* font, CvScalar color );
</pre><p><dl>
<dt>img<dd>Input image.
<dt>text<dd>String to print.
<dt>org<dd>Coordinates of the bottom-left corner of the first letter.
<dt>font<dd>Pointer to the font structure.
<dt>color<dd>Text color.
</dl><p>
The function <code>cvPutText</code> renders the text in the image with the specified font and
color. The printed text is clipped by ROI rectangle. Symbols that do not belong
to the specified font are replaced with the rectangle symbol.</p>


<hr><h3><a name="decl_cvGetTextSize">GetTextSize</a></h3>
<p class="Blurb">Retrieves width and height of text string</p>
<pre>
void cvGetTextSize( const char* text_string, const CvFont* font, CvSize* text_size, int* baseline );
</pre><p><dl>
<dt>font<dd>Pointer to the font structure.
<dt>text_string<dd>Input string.
<dt>text_size<dd>Resultant size of the text string. Height of the text does not include
the height of character parts that are below the baseline.
<dt>baseline<dd>y-coordinate of the baseline relatively to the bottom-most text point.
</dl><p>
The function <code>cvGetTextSize</code> calculates the binding rectangle for the given text
string when a specified font is used.</p>


<hr><h2><a name="cxcore_drawing_seq">Point Sets and Contours</a></h2>

<hr><h3><a name="decl_cvDrawContours">DrawContours</a></h3>
<p class="Blurb">Draws contour outlines or interiors in the image</p>
<pre>
void cvDrawContours( CvArr *img, CvSeq* contour,
                     CvScalar external_color, CvScalar hole_color,
                     int max_level, int thickness=1,
                     int line_type=8, CvPoint offset=cvPoint(0,0) );
</pre><p><dl>
<dt>img<dd>Image where the contours are to be drawn. Like in any other drawing
function, the contours are clipped with the ROI.
<dt>contour<dd>Pointer to the first contour.
<dt>external_color<dd>Color of the external contours.
<dt>hole_color<dd>Color of internal contours (holes).
<dt>max_level<dd>Maximal level for drawn contours. If 0, only <code>contour</code> is drawn. If
1, the contour and all contours after it on the same level are drawn. If 2, all
contours after and all contours one level below the contours are drawn, etc.
If the value is negative, the function does not draw the contours following after <code>contour</code>
but draws child contours of <code>contour</code> up to abs(<code>max_level</code>)-1 level.
<dt>thickness<dd>Thickness of lines the contours are drawn with. If it is negative (e.g. =CV_FILLED),
the contour interiors are drawn.
<dt>line_type<dd>Type of the contour segments, see <a href="#decl_cvLine">cvLine</a> description.
<dt>offset<dd>Shift all the point coordinates by the specified value.
              It is useful in case if the contours retrived in some image ROI and
              then the ROI offset needs to be taken into account during the rendering.
</dl><p>
The function <code>cvDrawContours</code> draws contour outlines in the image if <code>thickness</code>&gt;=0
or fills area bounded by the contours if <code>thickness</code>&lt;0.
</p>
<h4>Example. Connected component detection via contour functions</h4>
<pre>
#include "cv.h"
#include "highgui.h"

int main( int argc, char** argv )
{
    IplImage* src;
    // the first command line parameter must be file name of binary (black-n-white) image
    if( argc == 2 && (src=cvLoadImage(argv[1], 0))!= 0)
    {
        IplImage* dst = cvCreateImage( cvGetSize(src), 8, 3 );
        CvMemStorage* storage = cvCreateMemStorage(0);
        CvSeq* contour = 0;

        cvThreshold( src, src, 1, 255, CV_THRESH_BINARY );
        cvNamedWindow( "Source", 1 );
        cvShowImage( "Source", src );

        cvFindContours( src, storage, &amp;contour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
        cvZero( dst );

        for( ; contour != 0; contour = contour->h_next )
        {
            CvScalar color = CV_RGB( rand()&255, rand()&255, rand()&255 );
            /* replace CV_FILLED with 1 to see the outlines */
            cvDrawContours( dst, contour, color, color, -1, CV_FILLED, 8 );
        }

        cvNamedWindow( "Components", 1 );
        cvShowImage( "Components", dst );
        cvWaitKey(0);
    }
}
</pre>
<p>Replace CV_FILLED with 1 in the sample below to see the contour outlines
</p>


<hr><h3><a name="decl_cvInitLineIterator">InitLineIterator</a></h3>
<p class="Blurb">Initializes line iterator</p>
<pre>
int cvInitLineIterator( const CvArr* image, CvPoint pt1, CvPoint pt2,
                        CvLineIterator* line_iterator, int connectivity=8,
                        int left_to_right=0 );
</pre><p><dl>
<dt>image<dd>Image to sample the line from.
<dt>pt1<dd>First ending point of the line segment.
<dt>pt2<dd>Second ending point of the line segment.
<dt>line_iterator<dd>Pointer to the line iterator state structure.
<dt>connectivity<dd>The scanned line connectivity, 4 or 8.
<dt>left_to_right<dd>The flag, indicating whether the line should be always scanned from the
left-most point to the right-most out of <code>pt1</code> and <code>pt2</code> (<code>left_to_right&ne;0</code>),
or it is scanned in the specified order, from <code>pt1</code> to <code>pt2</code> (<code>left_to_right=0</code>).
</dl><p>
The function <code>cvInitLineIterator</code> initializes the line iterator and returns the
number of pixels between two end points. Both points must be inside the image.
After the iterator has been initialized, all the points on the raster line that
connects the two ending points may be retrieved by successive calls of
<code>CV_NEXT_LINE_POINT</code> point. The points on the line are calculated one by one using
4-connected or 8-connected Bresenham algorithm.</p>
<h4>Example. Using line iterator to calculate sum of pixel values along the color line</h4>
<pre>
    CvScalar sum_line_pixels( IplImage* image, CvPoint pt1, CvPoint pt2 )
    {
        CvLineIterator iterator;
        int blue_sum = 0, green_sum = 0, red_sum = 0;
        int count = cvInitLineIterator( image, pt1, pt2, &iterator, 8, 0 );

        for( int i = 0; i &lt; count; i++ ){
            blue_sum += iterator.ptr[0];
            green_sum += iterator.ptr[1];
            red_sum += iterator.ptr[2];
            CV_NEXT_LINE_POINT(iterator);

            /* print the pixel coordinates: demonstrates how to calculate the coordinates */
            {
            int offset, x, y;
            /* assume that ROI is not set, otherwise need to take it into account. */
            offset = iterator.ptr - (uchar*)(image->imageData);
            y = offset/image->widthStep;
            x = (offset - y*image->widthStep)/(3*sizeof(uchar) /* size of pixel */);
            printf("(%d,%d)\n", x, y );
            }
        }
        return cvScalar( blue_sum, green_sum, red_sum );
    }
</pre>


<hr><h3><a name="decl_cvClipLine">ClipLine</a></h3>
<p class="Blurb">Clips the line against the image rectangle</p>
<pre>
int cvClipLine( CvSize img_size, CvPoint* pt1, CvPoint* pt2 );
</pre><p><dl>
<dt>img_size<dd>Size of the image.
<dt>pt1<dd>First ending point of the line segment. It is modified by the function.
<dt>pt2<dd>Second ending point of the line segment. It is modified by the function.
</dl><p>
The function <code>cvClipLine</code> calculates a part of the line segment which is entirely in the image.
It returns 0 if the line segment is completely outside the image and 1 otherwise.
</p>


<hr><h3><a name="decl_cvEllipse2Poly">Ellipse2Poly</a></h3>
<p class="Blurb">Approximates elliptic arc with polyline</p>
<pre>
int cvEllipse2Poly( CvPoint center, CvSize axes,
                    int angle, int arc_start,
                    int arc_end, CvPoint* pts, int delta );
</pre><p><dl>
<dt>center<dd>Center of the arc.
<dt>axes<dd>Half-sizes of the arc. See <a href="#decl_cvEllipse">cvEllipse</a>.
<dt>angle<dd>Rotation angle of the ellipse in degrees. See <a href="#decl_cvEllipse">cvEllipse</a>.
<dt>start_angle<dd>Starting angle of the elliptic arc.
<dt>end_angle<dd>Ending angle of the elliptic arc.
<dt>pts<dd>The array of points, filled by the function.
<dt>delta<dd>Angle between the subsequent polyline vertices, approximation accuracy.
So, the total number of output points will ceil((end_angle - start_angle)/delta) + 1 at max.
</dl><p>
The function <code>cvEllipse2Poly</code> computes vertices of the polyline that approximates the specified elliptic arc.
It is used by <a href="#decl_cvEllipse">cvEllipse</a>.
</p>


<hr><h3><a name="decl_cvClipLine">ClipLine</a></h3>
CVAPI(int) cvEllipse2Poly( CvPoint center, CvSize axes,
                 int angle, int arc_start, int arc_end, CvPoint * pts, int delta );


<hr><h1><a name="cxcore_persistence">Data Persistence and RTTI</a></h1>

<hr><h2><a name="cxcore_persistence_ds">File Storage</a></h2>

<hr><h3><a name="decl_CvFileStorage">CvFileStorage</a></h3>
<p class="Blurb">File Storage</p>
<pre>
    typedef struct CvFileStorage
    {
        ...       // hidden fields
    } CvFileStorage;
</pre>
<p>
The structure <a href="#decl_CvFileStorage">CvFileStorage</a> is "black box" representation of
file storage that is associated with a file on disk. Several functions that are described below
take <code>CvFileStorage</code> on input and allow user to save or to load hierarchical collections
that consist of scalar values, standard CXCore objects (such as matrices, sequences, graphs) and
user-defined objects.
</p><p>
CXCore can read and write data in XML (<a href="http://www.w3c.org/XML">http://www.w3c.org/XML</a>)
or YAML (<a href="http://www.yaml.org">http://www.yaml.org</a>) formats. Below is the example of
3&times;3 floating-point identity matrix <code>A</code>, stored in XML and YAML files using CXCore functions:</p>
<p><dl>
<dt><b>XML:</b><dd><pre>
&lt;?xml version="1.0"&gt;
&lt;opencv_storage&gt;
&lt;A type_id="opencv-matrix"&gt;
  &lt;rows&gt;3&lt;/rows&gt;
  &lt;cols&gt;3&lt;/cols&gt;
  &lt;dt&gt;f&lt;/dt&gt;
  &lt;data&gt;1. 0. 0. 0. 1. 0. 0. 0. 1.&lt;/data&gt;
&lt;/A&gt;
&lt;/opencv_storage&gt;
</pre>
<dt><b>YAML:</b><dd><pre>
%YAML:1.0
A: !!opencv-matrix
  rows: 3
  cols: 3
  dt: f
  data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1.]
</pre>
</dl></p>
<p>
As it can be seen from the examples, XML uses nested tags to represent hierarchy,
while YAML uses indentation for that purpose (similarly to Python programming language).
</p><p>
The same CXCore functions can read and write data in both formats, the particular format is determined
by the extension of the opened file, .xml for XML files and .yml or .yaml for YAML.
</p>

<hr><h3><a name="decl_CvFileNode">CvFileNode</a></h3>
<p class="Blurb">File Storage Node</p>
<pre>
/* file node type */
#define CV_NODE_NONE        0
#define CV_NODE_INT         1
#define CV_NODE_INTEGER     CV_NODE_INT
#define CV_NODE_REAL        2
#define CV_NODE_FLOAT       CV_NODE_REAL
#define CV_NODE_STR         3
#define CV_NODE_STRING      CV_NODE_STR
#define CV_NODE_REF         4 /* not used */
#define CV_NODE_SEQ         5
#define CV_NODE_MAP         6
#define CV_NODE_TYPE_MASK   7

/* optional flags */
#define CV_NODE_USER        16
#define CV_NODE_EMPTY       32
#define CV_NODE_NAMED       64

#define CV_NODE_TYPE(tag)  ((tag) & CV_NODE_TYPE_MASK)

#define CV_NODE_IS_INT(tag)        (CV_NODE_TYPE(tag) == CV_NODE_INT)
#define CV_NODE_IS_REAL(tag)       (CV_NODE_TYPE(tag) == CV_NODE_REAL)
#define CV_NODE_IS_STRING(tag)     (CV_NODE_TYPE(tag) == CV_NODE_STRING)
#define CV_NODE_IS_SEQ(tag)        (CV_NODE_TYPE(tag) == CV_NODE_SEQ)
#define CV_NODE_IS_MAP(tag)        (CV_NODE_TYPE(tag) == CV_NODE_MAP)
#define CV_NODE_IS_COLLECTION(tag) (CV_NODE_TYPE(tag) >= CV_NODE_SEQ)
#define CV_NODE_IS_FLOW(tag)       (((tag) & CV_NODE_FLOW) != 0)
#define CV_NODE_IS_EMPTY(tag)      (((tag) & CV_NODE_EMPTY) != 0)
#define CV_NODE_IS_USER(tag)       (((tag) & CV_NODE_USER) != 0)
#define CV_NODE_HAS_NAME(tag)      (((tag) & CV_NODE_NAMED) != 0)

#define CV_NODE_SEQ_SIMPLE 256
#define CV_NODE_SEQ_IS_SIMPLE(seq) (((seq)->flags & CV_NODE_SEQ_SIMPLE) != 0)

typedef struct CvString
{
    int len;
    char* ptr;
}
CvString;

/* all the keys (names) of elements in the readed file storage
   are stored in the hash to speed up the lookup operations */
typedef struct CvStringHashNode
{
    unsigned hashval;
    CvString str;
    struct CvStringHashNode* next;
}
CvStringHashNode;

/* basic element of the file storage - scalar or collection */
typedef struct CvFileNode
{
    int tag;
    struct CvTypeInfo* info; /* type information
            (only for user-defined object, for others it is 0) */
    union
    {
        double f; /* scalar floating-point number */
        int i;    /* scalar integer number */
        CvString str; /* text string */
        CvSeq* seq; /* sequence (ordered collection of file nodes) */
        struct CvMap* map; /* map (collection of named file nodes) */
    } data;
}
CvFileNode;
</pre>
<p>
The structure is used only for retrieving data from file storage (i.e. for loading data from file).
When data is written to file, it is done sequentially, with minimal buffering. No data is stored in the
file storage.</p><p>In opposite, when data is read from file, the whole file is parsed and represented in memory
as a tree. Every node of the tree is represented by <a href="#decl_CvFileNode">CvFileNode</a>. Type of the file node
<code>N</code> can be retrieved as <code>CV_NODE_TYPE(N->tag)</code>. Some file nodes (leaves) are scalars:
text strings, integer or floating-point numbers. Other file nodes are collections of file nodes, which can
be scalars or collections in their turn. There are two types of collections: sequences and maps
(we use YAML notation, however, the same is true for XML streams). Sequences (do not mix them with
<a href="#decl_CvSeq">CvSeq</a>) are ordered collections of unnamed file nodes,
maps are unordered collections of named file nodes. Thus, elements of sequences are
accessed by index (<a href="#decl_cvGetSeqElem">cvGetSeqElem</a>),
while elements of maps are accessed by name
(<a href="#decl_cvGetFileNodeByName">cvGetFileNodeByName</a>).
The table below describes the different types of a file node:</p>
<p><table border=1 cellpadding="10%">
<tr><td>Type</td><td>CV_NODE_TYPE(node->tag)</td><td>Value</td></tr>
<tr><td>Integer</td><td>CV_NODE_INT</td><td>node->data.i</td></tr>
<tr><td>Floating-point</td><td>CV_NODE_REAL</td><td>node->data.f</td></tr>
<tr><td>Text string</td><td>CV_NODE_STR</td><td>node->data.str.ptr</td></tr>
<tr><td>Sequence</td><td>CV_NODE_SEQ</td><td>node->data.seq</td></tr>
<tr><td>Map</td><td>CV_NODE_MAP</td><td>node->data.map*</td></tr>
</table>
<dl>
<dt>*<dd>There is no need to access <code>map</code> field directly (BTW, <code>CvMap</code> is a hidden structure).
          The elements of the map can be retrieved with <a href="#decl_cvGetFileNodeByName">cvGetFileNodeByName</a>
          function that takes pointer to the "map" file node.
<!--
<dt>**<dd>Tag of the file node that represent a user object (see below) also includes <code>CV_NODE_USER</code> flag.
          That is, <code>CV_NODE_IS_USER(node->tag)</code> returns 1 on such a node.
<dt>***<dd>The field contains pointer to decoded object. The original map is still available as
          <code>node->data.obj.map</code>. -->
</dl>
</p><p>
A user (custom) object is instance of either one of standard CxCore types, such as <a href="#decl_CvMat">CvMat</a>, <a href="#decl_CvSeq">CvSeq</a> etc.,
or any type registered with <a href="#decl_cvRegisterTypeInfo">cvRegisterTypeInfo</a>. Such an object is initially represented in file as a map
(as shown in XML and YAML sample files above), after file storage has been opened and parsed.
Then the object can be decoded (coverted to the native representation) by request -
when user calls <a href="#decl_cvRead">cvRead</a> or
<a href="#decl_cvReadByName">cvReadByName</a> function.</p>

<hr><h3><a name="decl_CvAttrList">CvAttrList</a></h3>
<p class="Blurb">List of attributes</p>
<pre>
typedef struct CvAttrList
{
    const char** attr; /* NULL-terminated array of (attribute_name,attribute_value) pairs */
    struct CvAttrList* next; /* pointer to next chunk of the attributes list */
}
CvAttrList;

/* initializes CvAttrList structure */
inline CvAttrList cvAttrList( const char** attr=NULL, CvAttrList* next=NULL );

/* returns attribute value or 0 (NULL) if there is no such attribute */
const char* cvAttrValue( const CvAttrList* attr, const char* attr_name );
</pre>
<p>
In the current implementation attributes are used to pass extra parameters when writing user objects
(see <a href="#decl_cvWrite">cvWrite</a>).
XML attributes inside tags are not supported, besides the object type specification
(<code>type_id</code> attribute).
</p>


<hr><h3><a name="decl_cvOpenFileStorage">OpenFileStorage</a></h3>
<p class="Blurb">Opens file storage for reading or writing data</p>
<pre>
CvFileStorage* cvOpenFileStorage( const char* filename, CvMemStorage* memstorage, int flags );
</pre><p><dl>
<dt>filename<dd>Name of the file associated with the storage.
<dt>memstorage<dd>Memory storage used for temporary data and for storing dynamic structures,
such as <a href="#decl_CvSeq">CvSeq</a> or <a href="#decl_CvGraph">CvGraph</a>.
If it is NULL, a temporary memory storage is created and used.
<dt>flags<dd>Can be one of the following:<br>
            <code>CV_STORAGE_READ</code> - the storage is open for reading<br>
            <code>CV_STORAGE_WRITE</code> - the storage is open for writing<br>
</dl><p>
The function <code>cvOpenFileStorage</code> opens file storage for
reading or writing data. In the latter case a new file is created or existing file is
rewritten. Type of the read of written file is determined by the filename extension: <code>.xml</code>
for <em>XML</em>, and <code>.yml</code> or <code>.yaml</code> for <em>YAML</em>.
The function returns pointer to <a href="#decl_CvFileStorage">CvFileStorage</a> structure.</p>


<hr><h3><a name="decl_cvReleaseFileStorage">ReleaseFileStorage</a></h3>
<p class="Blurb">Releases file storage</p>
<pre>
void  cvReleaseFileStorage( CvFileStorage** fs );
</pre><p><dl>
<dt>fs<dd>Double pointer to the released file storage.
</dl><p>
The function <code>cvReleaseFileStorage</code> closes the file
associated with the storage and releases all the temporary structures.
It must be called after all I/O operations with the storage are finished.</p>


<hr><h2><a name="cxcore_persistence_writing">Writing Data</a></h2>

<hr><h3><a name="decl_cvStartWriteStruct">StartWriteStruct</a></h3>
<p class="Blurb">Starts writing a new structure</p>
<pre>
void  cvStartWriteStruct( CvFileStorage* fs, const char* name,
                          int struct_flags, const char* type_name=NULL,
                          CvAttrList attributes=cvAttrList());
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>name<dd>Name of the written structure. The structure can be accessed by this name when
            the storage is read.
<dt>struct_flags<dd>A combination one of the following values:<br>
              <code>CV_NODE_SEQ</code> - the written structure is a sequence (see discussion of
                <a href="#decl_CvFileStorage">CvFileStorage</a>), that is,
                its elements do not have a name. <br>
              <code>CV_NODE_MAP</code> - the written structure is a map (see discussion of
                <a href="#decl_CvFileStorage">CvFileStorage</a>), that is,
                all its elements have names. <br>
               <em>One and only one of the two above flags must be specified</em><br>
              <code>CV_NODE_FLOW</code> - the optional flag that has sense only for YAML streams.
                It means that the structure is written as a flow (not as a block), which is more
                compact. It is recommended to use this flag for structures or arrays whose elements are
                all scalars.
<dt>type_name<dd>Optional parameter - the object type name. In case of XML it is written as
                <code>type_id</code> attribute of the structure opening tag. In case of YAML
                it is written after a colon following the structure name (see the example in
                <a href="#decl_CvFileStorage">CvFileStorage</a> description).
                Mainly it comes with user objects.
                When the storage is read, the encoded type name is used to determine
                the object type (see <a href="#decl_CvTypeInfo">CvTypeInfo</a> and
                <a href="#decl_cvFindTypeInfo">cvFindTypeInfo</a>).
<dt>attributes<dd>This parameter is not used in the current implementation.
</dl><p>
The function <code>cvStartWriteStruct</code> starts writing
a compound structure (collection) that can be a sequence or a map. After all the structure
fields, which can be scalars or structures, are written,
<a href="#decl_cvEndWriteStruct">cvEndWriteStruct</a> should be called.
The function can be used to group some objects or to implement <em>write</em> function for a
some user object (see <a href="#decl_CvTypeInfo">CvTypeInfo</a>).
</p>


<hr><h3><a name="decl_cvEndWriteStruct">EndWriteStruct</a></h3>
<p class="Blurb">Ends writing a structure</p>
<pre>
void  cvEndWriteStruct( CvFileStorage* fs );
</pre><p><dl>
<dt>fs<dd>File storage.
</dl><p>
The function <code>cvEndWriteStruct</code> finishes the
currently written structure.</p>


<hr><h3><a name="decl_cvWriteInt">WriteInt</a></h3>
<p class="Blurb">Writes an integer value</p>
<pre>
void  cvWriteInt( CvFileStorage* fs, const char* name, int value );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>name<dd>Name of the written value. Should be NULL if and only if the
            parent structure is a sequence.
<dt>value<dd>The written value.
</dl><p>
The function <code>cvWriteInt</code> writes a single integer value
(with or without a name) to the file storage.</p>


<hr><h3><a name="decl_cvWriteReal">WriteReal</a></h3>
<p class="Blurb">Writes a floating-point value</p>
<pre>
void  cvWriteReal( CvFileStorage* fs, const char* name, double value );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>name<dd>Name of the written value. Should be NULL if and only if the
            parent structure is a sequence.
<dt>value<dd>The written value.
</dl><p>
The function <code>cvWriteReal</code> writes a single
floating-point value (with or without a name) to the file storage. The special
values are encoded: NaN (Not A Number) as .NaN, &plusmn;Infinity as +.Inf (-.Inf).</p>
<p>The following example shows how to use the low-level writing functions to
store custom structures, such as termination criteria, without registering
a new type.</p>
<pre>
void write_termcriteria( CvFileStorage* fs, const char* struct_name,
                         CvTermCriteria* termcrit )
{
    cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0));
    cvWriteComment( fs, "termination criteria", 1 ); // just a description
    if( termcrit->type & CV_TERMCRIT_ITER )
        cvWriteInteger( fs, "max_iterations", termcrit->max_iter );
    if( termcrit->type & CV_TERMCRIT_EPS )
        cvWriteReal( fs, "accuracy", termcrit->epsilon );
    cvEndWriteStruct( fs );
}
</pre>


<hr><h3><a name="decl_cvWriteString">WriteString</a></h3>
<p class="Blurb">Writes a text string</p>
<pre>
void  cvWriteString( CvFileStorage* fs, const char* name,
                     const char* str, int quote=0 );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>name<dd>Name of the written string. Should be NULL if and only if the
            parent structure is a sequence.
<dt>str<dd>The written text string.
<dt>quote<dd>If non-zero, the written string is put in quotes, regardless of whether
             they are required or not. Otherwise, if the flag is zero, quotes are used
             only when they are required (e.g. when the string starts with a digit or contains
             spaces).
</dl><p>
The function <code>cvWriteString</code> writes a text string
to the file storage.</p>


<hr><h3><a name="decl_cvWriteComment">WriteComment</a></h3>
<p class="Blurb">Writes comment</p>
<pre>
void  cvWriteComment( CvFileStorage* fs, const char* comment, int eol_comment );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>comment<dd>The written comment, single-line or multi-line.
<dt>eol_comment<dd>If non-zero, the function tries to put the comment in the end
             of current line. If the flag is zero, if the comment is multi-line, or
             if it does not fit in the end of the current line, the comment starts
             from a new line.
</dl><p>
The function <code>cvWriteComment</code> writes a comment into the
file storage. The comments are skipped when the storage is read, so they may be
used only for debugging or descriptive purposes.</p>


<hr><h3><a name="decl_cvStartNextStream">StartNextStream</a></h3>
<p class="Blurb">Starts the next stream</p>
<pre>
void  cvStartNextStream( CvFileStorage* fs );
</pre><p><dl>
<dt>fs<dd>File storage.
</dl><p>
The function <code>cvStartNextStream</code> starts the next
stream in the file storage. Both YAML and XML supports multiple "streams". This
is useful for concatenating files or for resuming the writing process.</p>


<hr><h3><a name="decl_cvWrite">Write</a></h3>
<p class="Blurb">Writes user object</p>
<pre>
void  cvWrite( CvFileStorage* fs, const char* name,
               const void* ptr, CvAttrList attributes=cvAttrList() );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>name<dd>Name, of the written object. Should be NULL if and only if the parent
            structure is a sequence.
<dt>ptr<dd>Pointer to the object.
<dt>attributes<dd>The attributes of the object. They are specific for each particular
           type (see the dicsussion).
</dl><p>
The function <code>cvWrite</code> writes the object to file storage.
First, the appropriate type info is found using <a href="#decl_cvTypeOf">cvTypeOf</a>.
Then, <code>write</code> method of the type info is called.
</p><p>
Attributes are used to customize the writing procedure.
The standard types support the following attributes
(all the <code>*dt</code> attributes have the same format as in
<a href="#decl_cvWriteRawData">cvWriteRawData</a>):
<dl>
<dt><a href="#decl_CvSeq">CvSeq</a><dd>
    <ul>
    <li><code>header_dt</code> - description
    of user fields of the sequence header that follow CvSeq, or CvChain
    (if the sequence is Freeman chain) or CvContour (if the sequence is a contour
    or point sequence)
    <li><code>dt</code> - description of the sequence elements.
    <li><code>recursive</code> - if the attribute is present and is not equal to "0" or "false",
    the whole tree of sequences (contours) is stored.
    </ul>
<dt><code>CvGraph</code><dd>
    <ul>
    <li><code>header_dt</code> - description of user fields
    of the graph header that follow CvGraph;
    <li><code>vertex_dt</code> - description of
    user fields of graph vertices
    <li><code>edge_dt</code> - description of user fields of graph edges (note, that
    edge weight is always written, so there is no need to specify it explicitly)
    </ul>
</dl>
</p><p>
Below is the code that creates the YAML file shown in <code>CvFileStorage</code>
description:</p><p>
<pre>
#include "cxcore.h"

int main( int argc, char** argv )
{
    CvMat* mat = cvCreateMat( 3, 3, CV_32F );
    CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE );

    cvSetIdentity( mat );
    cvWrite( fs, "A", mat, cvAttrList(0,0) );

    cvReleaseFileStorage( &fs );
    cvReleaseMat( &mat );
    return 0;
}
</pre></p>


<hr><h3><a name="decl_cvWriteRawData">WriteRawData</a></h3>
<p class="Blurb">Writes multiple numbers</p>
<pre>
void  cvWriteRawData( CvFileStorage* fs, const void* src,
                      int len, const char* dt );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>src<dd>Pointer to the written array
<dt>len<dd>Number of the array elements to write.
<dt>dt<dd>Specification of each array element that has the following format:
          <code>([count]{'u'|'c'|'w'|'s'|'i'|'f'|'d'})...</code>, where the characters
          correspond to fundamental C types:
          <ul>
              <li>'u' - 8-bit unsigned number
              <li>'c' - 8-bit signed number
              <li>'w' - 16-bit unsigned number
              <li>'s' - 16-bit signed number
              <li>'i' - 32-bit signed number
              <li>'f' - single precision floating-point number
              <li>'d' - double precision floating-point number
              <li>'r' - pointer. 32 lower bits of it are written as a signed
                        integer. The type can be used to store structures with
                        links between the elements.
          </ul>
          <code>count</code> is the optional counter of values of the certain type.
          For example, <code>dt='2if'</code> means that each array element is a structure
          of 2 integers, followed by a single-precision floating-point number. The equivalent
          notations of the above specification are <code>'iif'</code>, <code>'2i1f'</code> etc.
          Other examples: <code>dt='u'</code> means that the array consists of bytes,
          <code>dt='2d'</code> - the array consists of pairs of double&#146;s.
</dl><p>
The function <code>cvWriteRawData</code> writes array,
which elements consist of a single of multiple numbers. The function call can
be replaced with a loop containing a few <a href="#decl_cvWriteInt">cvWriteInt</a>
and <a href="#decl_cvWriteReal">cvWriteReal</a> calls,
but a single call is more efficient. Note, that because none of the elements
have a name, they should be written to a sequence rather than a map.</p>


<hr><h3><a name="decl_cvWriteFileNode">WriteFileNode</a></h3>
<p class="Blurb">Writes file node to another file storage</p>
<pre>
void cvWriteFileNode( CvFileStorage* fs, const char* new_node_name,
                      const CvFileNode* node, int embed );
</pre><dl>
<dt>fs<dd>Destination file storage.
<dt>new_file_node<dd>New name of the file node in the destination file storage.
                     To keep the existing name,
                     use <code><a href="#decl_cvGetFileNodeName">cvGetFileNodeName</a>(node)</code>.
<dt>node<dd>The written node
<dt>embed<dd>If the written node is a collection and this parameter is not zero,
             no extra level of hiararchy is created. Instead, all the elements of <code>node</code> are
             written into the currently written structure. Of course, map elements may be
             written only to map, and sequence elements may be written only to sequence.
</dl><p>
The function <code>cvWriteFileNode</code>
writes a copy of file node to file storage. The possible application of the function are:
merging several file storages into one. Conversion between XML and YAML formats etc.
</p>


<hr><h2><a name="cxcore_persistence_reading">Reading Data</a></h2>

<p>Data are retrieved from file storage in 2 steps:
first, the file node containing the requested data is found;
then, data is extracted from the node manually or using custom <code>read</code> method.</p>


<hr><h3><a name="decl_cvGetRootFileNode">GetRootFileNode</a></h3>
<p class="Blurb">Retrieves one of top-level nodes of the file storage</p>
<pre>
CvFileNode* cvGetRootFileNode( const CvFileStorage* fs, int stream_index=0 );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>stream_index<dd>Zero-based index of the stream. See <a href="#decl_cvStartNextStream">cvStartNextStream</a>.
           In most cases, there is only one stream in the file, however there can be several.
</dl><p>
The function <code>cvGetRootFileNode</code> returns
one of  top-level file nodes. The top-level nodes do not have a name, they correspond to
the streams, that are stored one after another in the file storage.
If the index is out of range, the function returns NULL pointer, so all the top-level
nodes may be iterated by subsequent calls to the function with <code>stream_index=0,1,...</code>,
until NULL pointer is returned. This function may be used as a base for recursive traversal of the
file storage.</p>


<hr><h3><a name="decl_cvGetFileNodeByName">GetFileNodeByName</a></h3>
<p class="Blurb">Finds node in the map or file storage</p>
<pre>
CvFileNode* cvGetFileNodeByName( const CvFileStorage* fs,
                                 const CvFileNode* map,
                                 const char* name );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>map<dd>The parent map. If it is NULL, the function searches
           in all the top-level nodes (streams), starting from the first one.
<dt>name<dd>The file node name.
</dl><p>
The function <code>cvGetFileNodeByName</code> finds
a file node by <code>name</code>. The node is searched either in <code>map</code>
or, if the pointer is NULL, among the top-level file nodes of the storage.
Using this function for maps and <a href="#decl_cvGetSeqElem">cvGetSeqElem</a>
(or sequence reader) for sequences, it is possible to nagivate through the file storage.
To speed up multiple queries for a certain key (e.g. in case of array of structures)
one may use a pair of <a href="#decl_cvGetHashedKey">cvGetHashedKey</a> and
<a href="#decl_cvGetFileNode">cvGetFileNode</a>.</p>


<hr><h3><a name="decl_cvGetHashedKey">GetHashedKey</a></h3>
<p class="Blurb">Returns a unique pointer for given name</p>
<pre>
CvStringHashNode* cvGetHashedKey( CvFileStorage* fs, const char* name,
                                  int len=-1, int create_missing=0 );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>name<dd>Literal node name.
<dt>len<dd>Length of the name (if it is known apriori), or -1 if it needs to
           be calculated.
<dt>create_missing<dd>Flag that specifies, whether an absent key should be
           added into the hash table, or not.
</dl><p>
The function <code>cvGetHashedKey</code> returns
the unique pointer for each particular file node name. This pointer can be
then passed to <a href="#decl_cvGetFileNode">cvGetFileNode</a> function that
is faster than <a href="#decl_cvGetFileNodeByName">cvGetFileNodeByName</a>
because it compares text strings by comparing pointers rather than the
strings' content.</p><p>Consider the following example: an array of points
is encoded as a sequence of 2-entry maps, e.g.:
<pre>
%YAML:1.0
points:
  - { x: 10, y: 10 }
  - { x: 20, y: 20 }
  - { x: 30, y: 30 }
  # ...
</pre>
Then, it is possible to get hashed "x" and "y" pointers to speed up
decoding of the points.
<h4>Example. Reading an array of structures from file storage</h4>
<pre>
#include "cxcore.h"

int main( int argc, char** argv )
{
    CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ );
    CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 );
    CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 );
    CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" );

    if( CV_NODE_IS_SEQ(points->tag) )
    {
        CvSeq* seq = points->data.seq;
        int i, total = seq->total;
        CvSeqReader reader;
        cvStartReadSeq( seq, &reader, 0 );
        for( i = 0; i &lt; total; i++ )
        {
            CvFileNode* pt = (CvFileNode*)reader.ptr;
#if 1 /* faster variant */
            CvFileNode* xnode = cvGetFileNode( fs, pt, x_key, 0 );
            CvFileNode* ynode = cvGetFileNode( fs, pt, y_key, 0 );
            assert( xnode && CV_NODE_IS_INT(xnode->tag) &&
                    ynode && CV_NODE_IS_INT(ynode->tag));
            int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
            int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
#elif 1 /* slower variant; does not use x_key & y_key */
            CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" );
            CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" );
            assert( xnode && CV_NODE_IS_INT(xnode->tag) &&
                    ynode && CV_NODE_IS_INT(ynode->tag));
            int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
            int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
#else /* the slowest yet the easiest to use variant */
            int x = cvReadIntByName( fs, pt, "x", 0 /* default value */ );
            int y = cvReadIntByName( fs, pt, "y", 0 /* default value */ );
#endif
            CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
            printf("%d: (%d, %d)\n", i, x, y );
        }
    }
    cvReleaseFileStorage( &fs );
    return 0;
}
</pre>
<p>Please note that, whatever method of accessing map you are using,
it is still <em>much</em> slower than using plain sequences, for example,
in the above sample, it is more efficient to encode the points as pairs of
integers in the single numeric sequence.</p>


<hr><h3><a name="decl_cvGetFileNode">GetFileNode</a></h3>
<p class="Blurb">Finds node in the map or file storage</p>
<pre>
CvFileNode* cvGetFileNode( CvFileStorage* fs, CvFileNode* map,
                           const CvStringHashNode* key, int create_missing=0 );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>map<dd>The parent map. If it is NULL, the function searches a top-level node.
           If both <code>map</code> and <code>key</code> are NULLs,
           the function returns the root file node - a map
           that contains top-level nodes.
<dt>key<dd>Unique pointer to the node name, retrieved with
           <a href="#decl_cvGetHashedKey">cvGetHashedKey</a>.
<dt>create_missing<dd>Flag that specifies, whether an absent node should be
           added to the map, or not.
</dl><p>
The function <code>cvGetFileNode</code> finds a file node. It is
a faster version <a href="#decl_cvGetFileNodeByName">cvGetFileNodeByName</a>
(see <a href="#decl_cvGetHashedKey">cvGetHashedKey</a> discussion). Also,
the function can insert a new node, if it is not in the map yet (which is used
by parsing functions).</p>


<hr><h3><a name="decl_cvGetFileNodeName">GetFileNodeName</a></h3>
<p class="Blurb">Returns name of file node</p>
<pre>
const char* cvGetFileNodeName( const CvFileNode* node );
</pre><p><dl>
<dt>node<dd>File node
</dl><p>
The function <code>cvGetFileNodeName</code> returns name of the file node
or NULL, if the file node does not have a name, or if <code>node</code> is <code>NULL</code>.</p>


<hr><h3><a name="decl_cvReadInt">ReadInt</a></h3>
<p class="Blurb">Retrieves integer value from file node</p>
<pre>
int cvReadInt( const CvFileNode* node, int default_value=0 );
</pre><p><dl>
<dt>node<dd>File node.
<dt>default_value<dd>The value that is returned if <code>node</code> is NULL.
</dl><p>
The function <code>cvReadInt</code> returns integer that is
represented by the file node. If the file node is NULL, <code>default_value</code>
is returned (thus, it is convenient to call the function right after
<a href="#decl_cvGetFileNode">cvGetFileNode</a> without checking for NULL pointer),
otherwise if the file node has type <code>CV_NODE_INT</code>,
then <code>node->data.i</code> is returned, otherwise if the file node has
type <code>CV_NODE_REAL</code>, then <code>node->data.f</code>
is converted to integer and returned, otherwise the result is not determined.</p>


<hr><h3><a name="decl_cvReadIntByName">ReadIntByName</a></h3>
<p class="Blurb">Finds file node and returns its value</p>
<pre>
int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map,
                     const char* name, int default_value=0 );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>map<dd>The parent map. If it is NULL, the function searches a top-level node.
<dt>name<dd>The node name.
<dt>default_value<dd>The value that is returned if the file node is not found.
</dl><p>
The function <code>cvReadIntByName</code> is a simple
superposition of <a href="#decl_cvGetFileNodeByName">cvGetFileNodeByName</a> and
<a href="#decl_cvReadInt">cvReadInt</a>.


<hr><h3><a name="decl_cvReadReal">ReadReal</a></h3>
<p class="Blurb">Retrieves floating-point value from file node</p>
<pre>
double cvReadReal( const CvFileNode* node, double default_value=0. );
</pre><p><dl>
<dt>node<dd>File node.
<dt>default_value<dd>The value that is returned if <code>node</code> is NULL.
</dl><p>
The function <code>cvReadReal</code> returns floating-point value that is
represented by the file node. If the file node is NULL, <code>default_value</code>
is returned (thus, it is convenient to call the function right after
<a href="#decl_cvGetFileNode">cvGetFileNode</a> without checking for NULL pointer),
otherwise if the file node has type <code>CV_NODE_REAL</code>,
then <code>node->data.f</code> is returned, otherwise if the file node has
type <code>CV_NODE_INT</code>, then <code>node->data.f</code>
is converted to floating-point and returned, otherwise the result is not determined.</p>


<hr><h3><a name="decl_cvReadRealByName">ReadRealByName</a></h3>
<p class="Blurb">Finds file node and returns its value</p>
<pre>
double  cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map,
                          const char* name, double default_value=0. );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>map<dd>The parent map. If it is NULL, the function searches a top-level node.
<dt>name<dd>The node name.
<dt>default_value<dd>The value that is returned if the file node is not found.
</dl><p>
The function <code>cvReadRealByName</code> is a simple
superposition of <a href="#decl_cvGetFileNodeByName">cvGetFileNodeByName</a> and
<a href="#decl_cvReadReal">cvReadReal</a>.


<hr><h3><a name="decl_cvReadString">ReadString</a></h3>
<p class="Blurb">Retrieves text string from file node</p>
<pre>
const char* cvReadString( const CvFileNode* node, const char* default_value=NULL );
</pre><p><dl>
<dt>node<dd>File node.
<dt>default_value<dd>The value that is returned if <code>node</code> is NULL.
</dl><p>
The function <code>cvReadString</code> returns text string that is
represented by the file node. If the file node is NULL, <code>default_value</code>
is returned (thus, it is convenient to call the function right after
<a href="#decl_cvGetFileNode">cvGetFileNode</a> without checking for NULL pointer),
otherwise if the file node has type <code>CV_NODE_STR</code>,
then <code>node->data.str.ptr</code> is returned, otherwise the result is not determined.</p>


<hr><h3><a name="decl_cvReadStringByName">ReadStringByName</a></h3>
<p class="Blurb">Finds file node and returns its value</p>
<pre>
const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map,
                                const char* name, const char* default_value=NULL );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>map<dd>The parent map. If it is NULL, the function searches a top-level node.
<dt>name<dd>The node name.
<dt>default_value<dd>The value that is returned if the file node is not found.
</dl><p>
The function <code>cvReadStringByName</code> is a simple
superposition of <a href="#decl_cvGetFileNodeByName">cvGetFileNodeByName</a> and
<a href="#decl_cvReadString">cvReadString</a>.


<hr><h3><a name="decl_cvRead">Read</a></h3>
<p class="Blurb">Decodes object and returns pointer to it</p>
<pre>
void* cvRead( CvFileStorage* fs, CvFileNode* node,
              CvAttrList* attributes=NULL );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>node<dd>The root object node.
<dt>attributes<dd>Unused parameter.
</dl><p>
The function <code>cvRead</code> decodes user object (creates object
in a native representation from the file storage subtree) and returns it.
The object to be decoded must be an instance of registered type that supports <code>read</code>
method (see <a href="#decl_CvTypeInfo">CvTypeInfo</a>). Type of the object is determined by
the type name that is encoded in the file. If the object is dynamic structure, it is
created either in memory storage, passed to <a href="#decl_cvOpenFileStorage">cvOpenFileStorage</a>
or, if NULL pointer was passed, in temporary memory storage, which is release when
<a href="#decl_cvReleaseFileStorage">cvReleaseFileStorage</a> is called.
Otherwise, if the object is not a dynamic structure, it is created in heap and should be
released with a specialized function or using generic <a href="#decl_cvRelease">cvRelease</a>.</p>


<hr><h3><a name="decl_cvReadByName">ReadByName</a></h3>
<p class="Blurb">Finds object and decodes it</p>
<pre>
void* cvReadByName( CvFileStorage* fs, const CvFileNode* map,
                    const char* name, CvAttrList* attributes=NULL );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>map<dd>The parent map. If it is NULL, the function searches a top-level node.
<dt>name<dd>The node name.
<dt>attributes<dd>Unused parameter.
</dl><p>
The function <code>cvReadByName</code> is a simple
superposition of <a href="#decl_cvGetFileNodeByName">cvGetFileNodeByName</a> and
<a href="#decl_cvRead">cvRead</a>.


<hr><h3><a name="decl_cvReadRawData">ReadRawData</a></h3>
<p class="Blurb">Reads multiple numbers</p>
<pre>
void cvReadRawData( const CvFileStorage* fs, const CvFileNode* src,
                    void* dst, const char* dt );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>src<dd>The file node (a sequence) to read numbers from.
<dt>dst<dd>Pointer to the destination array.
<dt>dt<dd>Specification of each array element. It has the same format as in
          <a href="#decl_cvWriteRawData">cvWriteRawData</a>.
</dl><p>
The function <code>cvReadRawData</code> reads elements
from a file node that represents a sequence of scalars</p>


<hr><h3><a name="decl_cvStartReadRawData">StartReadRawData</a></h3>
<p class="Blurb">Initializes file node sequence reader</p>
<pre>
void cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src,
                         CvSeqReader* reader );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>src<dd>The file node (a sequence) to read numbers from.
<dt>reader<dd>Pointer to the sequence reader.
</dl><p>
The function <code>cvStartReadRawData</code> initializes
sequence reader to read data from file node. The initialized reader can be then
passed to <a href="#decl_cvReadRawDataSlice">cvReadRawDataSlice</a>.</p>


<hr><h3><a name="decl_cvReadRawDataSlice">ReadRawDataSlice</a></h3>
<p class="Blurb">Initializes file node sequence reader</p>
<pre>
void cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader,
                         int count, void* dst, const char* dt );
</pre><p><dl>
<dt>fs<dd>File storage.
<dt>reader<dd>The sequence reader. Initialize it with <a href="#decl_cvStartReadRawData">cvStartReadRawData</a>.
<dt>count<dd>The number of elements to read.
<dt>dst<dd>Pointer to the destination array.
<dt>dt<dd>Specification of each array element. It has the same format as in
          <a href="#decl_cvWriteRawData">cvWriteRawData</a>.
</dl><p>
The function <code>cvReadRawDataSlice</code> reads one
or more elements from the file node, representing a sequence, to user-specified
array. The total number of read sequence elements is a product of <code>total</code>
and the number of components in each array element.
For example, if <code>dt='2if'</code>, the function will read <code>total*3</code> sequence elements.
As with any sequence, some parts of the file node sequence may be skipped or read repeatedly
by repositioning the reader using <a href="#decl_cvSetSeqReaderPos">cvSetSeqReaderPos</a>.</p>


<hr><h2><a name="cxcore_persistence_rtti">RTTI and Generic Functions</a></h2>


<hr><h3><a name="decl_CvTypeInfo">CvTypeInfo</a></h3>
<p class="Blurb">Type information</p>
<pre>
typedef int (CV_CDECL *CvIsInstanceFunc)( const void* struct_ptr );
typedef void (CV_CDECL *CvReleaseFunc)( void** struct_dblptr );
typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node );
typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage,
                                      const char* name,
                                      const void* struct_ptr,
                                      CvAttrList attributes );
typedef void* (CV_CDECL *CvCloneFunc)( const void* struct_ptr );

typedef struct CvTypeInfo
{
    int flags; /* not used */
    int header_size; /* sizeof(CvTypeInfo) */
    struct CvTypeInfo* prev; /* previous registered type in the list */
    struct CvTypeInfo* next; /* next registered type in the list */
    const char* type_name; /* type name, written to file storage */

    /* methods */
    CvIsInstanceFunc is_instance; /* checks if the passed object belongs to the type */
    CvReleaseFunc release; /* releases object (memory etc.) */
    CvReadFunc read; /* reads object from file storage */
    CvWriteFunc write; /* writes object to file storage */
    CvCloneFunc clone; /* creates a copy of the object */
}
CvTypeInfo;
</pre><p>
The structure <a href="#decl_CvTypeInfo">CvTypeInfo</a> contains information about
one of standard or user-defined types. Instances of the type may or may not contain
pointer to the corresponding <a href="#decl_CvTypeInfo">CvTypeInfo</a> structure.
In any case there is a way to find type info structure for given object - using
<a href="#decl_cvTypeOf">cvTypeOf</a> function. Aternatively, type info can be
found by the type name using <a href="#decl_cvFindType">cvFindType</a>, which is
used when object is read from file storage. User can register a new type with
<a href="#decl_cvRegisterType">cvRegisterType</a> that adds the type information structure
into the beginning of the type list - thus, it is possible to create specialized types
from generic standard types and override the basic methods.
<p>


<hr><h3><a name="decl_cvRegisterType">RegisterType</a></h3>
<p class="Blurb">Registers new type</p>
<pre>
void cvRegisterType( const CvTypeInfo* info );
</pre><p><dl>
<dt>info<dd>Type info structure.
</dl><p>
The function <code>cvRegisterType</code> registers a new type,
which is described by <code>info</code>. The function creates a copy of the structure,
so user should delete it after calling the function.</p>


<hr><h3><a name="decl_cvUnregisterType">UnregisterType</a></h3>
<p class="Blurb">Unregisters the type</p>
<pre>
void cvUnregisterType( const char* type_name );
</pre><p><dl>
<dt>type_name<dd>Name of the unregistered type.
</dl><p>
The function <code>cvUnregisterType</code> unregisters the type
with the specified name. If the name is unknown, it is possible to locate the type info
by an instance of the type using <a href="#decl_cvTypeOf">cvTypeOf</a> or by iterating
the type list, starting from <a href="#decl_cvFirstType">cvFirstType</a>, and then
call <code><a href="#decl_cvUnregisterType">cvUnregisterType</a>(info->type_name)</code>.</p>


<hr><h3><a name="decl_cvFirstType">FirstType</a></h3>
<p class="Blurb">Returns the beginning of type list</p>
<pre>
CvTypeInfo* cvFirstType( void );
</pre><p>
The function <code>cvFirstType</code> returns the first type of the list
of registered types. Navigation through the list can be done via <code>prev</code> and <code>next</code>
fields of <a href="#decl_CvTypeInfo">CvTypeInfo</a> structure.</p>


<hr><h3><a name="decl_cvFindType">FindType</a></h3>
<p class="Blurb">Finds type by its name</p>
<pre>
CvTypeInfo* cvFindType( const char* type_name );
</pre><p><dl>
<dt>type_name<dd>Type name.
</dl><p>
The function <code>cvFindType</code> finds a registered type by its name.
It returns NULL, if there is no type with the specified name.</p>


<hr><h3><a name="decl_cvTypeOf">TypeOf</a></h3>
<p class="Blurb">Returns type of the object</p>
<pre>
CvTypeInfo* cvTypeOf( const void* struct_ptr );
</pre><p><dl>
<dt>struct_ptr<dd>The object pointer.
</dl><p>
The function <code>cvTypeOf</code> finds the type of given object. It iterates through the list
of registered types and calls <code>is_instance</code> function/method of every type info structure with
the object until one of them return non-zero or until the whole list has been traversed. In the latter
case the function returns NULL.</p>


<hr><h3><a name="decl_cvRelease">Release</a></h3>
<p class="Blurb">Releases the object</p>
<pre>
void cvRelease( void** struct_ptr );
</pre><p><dl>
<dt>struct_ptr<dd>Double pointer to the object.
</dl><p>
The function <code>cvRelease</code> finds the type of given object and calls
<code>release</code> with the double pointer.</p>


<hr><h3><a name="decl_cvClone">Clone</a></h3>
<p class="Blurb">Makes a clone of the object</p>
<pre>
void* cvClone( const void* struct_ptr );
</pre><p><dl>
<dt>struct_ptr<dd>The object to clone.
</dl><p>
The function <code>cvClone</code> finds the type of given object and calls
<code>clone</code> with the passed object.</p>


<hr><h3><a name="decl_cvSave">Save</a></h3>
<p class="Blurb">Saves object to file</p>
<pre>
void cvSave( const char* filename, const void* struct_ptr,
             const char* name=NULL,
             const char* comment=NULL,
             CvAttrList attributes=cvAttrList());
</pre><p><dl>
<dt>filename<dd>File name.
<dt>struct_ptr<dd>Object to save.
<dt>name<dd>Optional object name. If it is NULL, the name will be formed from <code>filename</code>.
<dt>comment<dd>Optional comment to put in the beginning of the file.
<dt>attributes<dd>Optional attributes passed to <a href="#decl_cvWrite">cvWrite</a>.
</dl><p>
The function <code>cvSave</code> saves object to file. It provides a simple interface
to <a href="#decl_cvWrite">cvWrite</a>.</p>


<hr><h3><a name="decl_cvLoad">Load</a></h3>
<p class="Blurb">Loads object from file</p>
<pre>
void* cvLoad( const char* filename, CvMemStorage* memstorage=NULL,
              const char* name=NULL, const char** real_name=NULL );
</pre><p><dl>
<dt>filename<dd>File name.
<dt>memstorage<dd>Memory storage for dynamic structures, such as <a href="#decl_CvSeq">CvSeq</a>
                  or <a href="#decl_CvGraph">CvGraph</a>. It is not used for matrices or images.
<dt>name<dd>Optional object name. If it is NULL, the first top-level object in the storage will be loaded.
<dt>real_name<dd>Optional output parameter that will contain name of the loaded object
                 (useful if <code>name=NULL</code>).
</dl><p>
The function <code>cvLoad</code> loads object from file.
It provides a simple interface to <a href="#decl_cvRead">cvRead</a>.
After object is loaded,
the file storage is closed and all the temporary buffers are deleted. Thus, to load a dynamic structure,
such as sequence, contour or graph, one should pass a valid destination
memory storage to the function.</p>


<hr><h1><a name="cxcore_misc">Miscellaneous Functions</a></h1>

<hr><h3><a name="decl_cvCheckArr">CheckArr</a></h3>
<p class="Blurb">Checks every element of input array for invalid values</p>
<pre>
int  cvCheckArr( const CvArr* arr, int flags=0,
                 double min_val=0, double max_val=0);
#define cvCheckArray cvCheckArr
</pre><p><dl>
<dt>arr<dd>The array to check.
<dt>flags<dd>The operation flags, 0 or combination of:<br>
             <code>CV_CHECK_RANGE</code> - if set, the function checks that every value of
                              array is within [minVal,maxVal) range,
                              otherwise it just checks that every element
                              is neigther NaN nor &plusmn;Infinity.<br>
             <code>CV_CHECK_QUIET</code> - if set, the function does not raises an
                              error if an element is invalid or out of range
<dt>min_val<dd>The inclusive lower boundary of valid values range.
              It is used only if <code>CV_CHECK_RANGE</code> is set.
<dt>max_val<dd>The exclusive upper boundary of valid values range.
              It is used only if <code>CV_CHECK_RANGE</code> is set.
</dl><p>
The function <code>cvCheckArr</code> checks that every array element
is neither NaN nor &plusmn;Infinity.
If <code>CV_CHECK_RANGE</code> is set, it also checks that every element is
greater than or equal to <code>minVal</code> and less than <code>maxVal</code>.
The function returns nonzero if the check succeeded, i.e. all elements
are valid and within the range, and zero otherwise.
In the latter case if <code>CV_CHECK_QUIET</code> flag is not set, the function
raises runtime error.
</p>


<hr><h3><a name="decl_cvKMeans2">KMeans2</a></h3>
<p class="Blurb">Splits set of vectors by given number of clusters</p>
<pre>
void cvKMeans2( const CvArr* samples, int cluster_count,
                CvArr* labels, CvTermCriteria termcrit );
</pre><p><dl>
<dt>samples<dd>Floating-point matrix of input samples, one row per sample.
<dt>cluster_count<dd>Number of clusters to split the set by.
<dt>labels<dd>Output integer vector storing cluster indices for every sample.
<dt>termcrit<dd>Specifies maximum number of iterations and/or accuracy (distance the centers move by
between the subsequent iterations).
</dl><p>
The function <code>cvKMeans2</code> implements k-means algorithm that finds centers of <code>cluster_count</code> clusters
and groups the input samples around the clusters. On output <code>labels(i)</code> contains a cluster index
for sample stored in the i-th row of <code>samples</code> matrix.
<h4>Example. Clustering random samples of multi-gaussian distribution with k-means</h4>
<pre>
#include "cxcore.h"
#include "highgui.h"

void main( int argc, char** argv )
{
    #define MAX_CLUSTERS 5
    CvScalar color_tab[MAX_CLUSTERS];
    IplImage* img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
    CvRNG rng = cvRNG(0xffffffff);
    
    color_tab[0] = CV_RGB(255,0,0);
    color_tab[1] = CV_RGB(0,255,0);
    color_tab[2] = CV_RGB(100,100,255);
    color_tab[3] = CV_RGB(255,0,255);
    color_tab[4] = CV_RGB(255,255,0);

    cvNamedWindow( "clusters", 1 );

    for(;;)
    {
        int k, cluster_count = cvRandInt(&rng)%MAX_CLUSTERS + 1;
        int i, sample_count = cvRandInt(&rng)%1000 + 1;
        CvMat* points = cvCreateMat( sample_count, 1, CV_32FC2 );
        CvMat* clusters = cvCreateMat( sample_count, 1, CV_32SC1 );

        /* generate random sample from multigaussian distribution */
        for( k = 0; k &lt; cluster_count; k++ )
        {
            CvPoint center;
            CvMat point_chunk;
            center.x = cvRandInt(&rng)%img->width;
            center.y = cvRandInt(&rng)%img->height;
            cvGetRows( points, &point_chunk, k*sample_count/cluster_count,
                       k == cluster_count - 1 ? sample_count : (k+1)*sample_count/cluster_count );
            cvRandArr( &rng, &point_chunk, CV_RAND_NORMAL,
                       cvScalar(center.x,center.y,0,0),
                       cvScalar(img->width/6, img->height/6,0,0) );
        }

        /* shuffle samples */
        for( i = 0; i &lt; sample_count/2; i++ )
        {
            CvPoint2D32f* pt1 = (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
            CvPoint2D32f* pt2 = (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
            CvPoint2D32f temp;
            CV_SWAP( *pt1, *pt2, temp );
        }

        cvKMeans2( points, cluster_count, clusters,
                   cvTermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0 ));

        cvZero( img );

        for( i = 0; i &lt; sample_count; i++ )
        {
            CvPoint2D32f pt = ((CvPoint2D32f*)points->data.fl)[i];
            int cluster_idx = clusters->data.i[i];
            cvCircle( img, cvPointFrom32f(pt), 2, color_tab[cluster_idx], CV_FILLED );
        }

        cvReleaseMat( &amp;points );
        cvReleaseMat( &amp;clusters );

        cvShowImage( "clusters", img );

        int key = cvWaitKey(0);
        if( key == 27 ) // 'ESC'
            break;
    }
}
</pre>


<hr><h3><a name="decl_cvSeqPartition">SeqPartition</a></h3>
<p class="Blurb">Splits sequence into equivalency classes</p>
<pre>
typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
int cvSeqPartition( const CvSeq* seq, CvMemStorage* storage, CvSeq** labels,
                    CvCmpFunc is_equal, void* userdata );
</pre><p><dl>
<dt>seq<dd>The sequence to partition.
<dt>storage<dd>The storage to store the sequence of equivalency classes. If it is NULL,
               the function uses <code>seq->storage</code> for output labels.
<dt>labels<dd>Ouput parameter. Double pointer to the sequence
              of 0-based labels of input sequence elements.
<dt>is_equal<dd>The relation function that should return non-zero if the two particular sequence elements
                are from the same class, and zero overwise.
                The partitioning algorithm uses transitive closure of the relation function as equivalency critria.
<dt>userdata<dd>Pointer that is transparently passed to the <code>is_equal</code> function.
</dl><p>
The function <code>cvSeqPartition</code> implements quadratic algorithm for splitting
a set into one or more classes of equivalency. The function returns the number of equivalency classes.
</p>
<h4>Example. Partitioning 2d point set.</h4>
<pre>
#include "cxcore.h"
#include "highgui.h"
#include &lt;stdio.h&gt;

CvSeq* point_seq = 0;
IplImage* canvas = 0;
CvScalar* colors = 0;
int pos = 10;

int is_equal( const void* _a, const void* _b, void* userdata )
{
    CvPoint a = *(const CvPoint*)_a;
    CvPoint b = *(const CvPoint*)_b;
    double threshold = *(double*)userdata;
    return (double)(a.x - b.x)*(a.x - b.x) + (double)(a.y - b.y)*(a.y - b.y) &lt;= threshold;
}

void on_track( int pos )
{
    CvSeq* labels = 0;
    double threshold = pos*pos;
    int i, class_count = cvSeqPartition( point_seq, 0, &labels, is_equal, &threshold );
    printf("%4d classes\n", class_count );
    cvZero( canvas );

    for( i = 0; i &lt; labels-&gt;total; i++ )
    {
        CvPoint pt = *(CvPoint*)cvGetSeqElem( point_seq, i, 0 );
        CvScalar color = colors[*(int*)cvGetSeqElem( labels, i, 0 )];
        cvCircle( canvas, pt, 1, color, -1 );
    }

    cvShowImage( "points", canvas );
}

int main( int argc, char** argv )
{
    CvMemStorage* storage = cvCreateMemStorage(0);
    point_seq = cvCreateSeq( CV_32SC2, sizeof(CvSeq), sizeof(CvPoint), storage );
    CvRNG rng = cvRNG(0xffffffff);

    int width = 500, height = 500;
    int i, count = 1000;
    canvas = cvCreateImage( cvSize(width,height), 8, 3 );

    colors = (CvScalar*)cvAlloc( count*sizeof(colors[0]) );
    for( i = 0; i &lt; count; i++ )
    {
        CvPoint pt;
        int icolor;
        pt.x = cvRandInt( &rng ) % width;
        pt.y = cvRandInt( &rng ) % height;
        cvSeqPush( point_seq, &pt );
        icolor = cvRandInt( &rng ) | 0x00404040;
        colors[i] = CV_RGB(icolor & 255, (icolor >> 8)&255, (icolor >> 16)&255);
    }

    cvNamedWindow( "points", 1 );
    cvCreateTrackbar( "threshold", "points", &pos, 50, on_track );
    on_track(pos);
    cvWaitKey(0);
    return 0;
}
</pre>


<hr><h1><a name="cxcore_system">Error Handling and System Functions</a></h1>

<hr><h2><a name="cxcore_system_error">Error Handling</a></h2>

<p>Error handling in OpenCV is similar to IPL (Image Processing Library).
In case of error functions do not return the error code. Instead, they raise
an error using <a href="#decl_error_macros">CV_ERROR</a> macro that calls
<a href="#decl_cvError">cvError</a> that, in its turn, sets the error status
with <a href="#decl_cvSetErrStatus">cvSetErrStatus</a> and
calls a standard or user-defined error handler (that can display a message box,
write to log etc., see <a href="#decl_cvRedirectError">cvRedirectError</a>,
<a href="#decl_cvNulDevReport">cvNulDevReport, cvStdErrReport, cvGuiBoxReport</a>).
There is global variable, one per each program thread, that contains current
error status (an integer value). The status can be retrieved with
<a href="#decl_cvGetErrStatus">cvGetErrStatus</a> function.
</p>
<p>
There are three modes of error handling (see <a href="#decl_cvSetErrMode">cvSetErrMode</a>
and <a href="#decl_cvGetErrMode">cvGetErrMode</a>):
<dl>
<dt>Leaf<dd>The program is terminated after error handler is called.
            <em>This is the default value</em>. It is useful for debugging, as the error
            is signalled immediately after it occurs. However, for production systems
            other two methods may be prefferable as they provide more control.
<dt>Parent<dd>The program is not terminated, but the error handler is called.
              The stack is unwinded (it is done w/o using C++ exception mechanism).
              User may check error code after calling CxCore function with
              <a href="#decl_cvGetErrStatus">cvGetErrStatus</a> and react.
<dt>Silent<dd>Similar to <em>Parent</em> mode, but no error handler is called.
</dl>
<p>Actually, the semantics of <em>Leaf</em> and <em>Parent</em> modes is implemented by
error handlers and the above description is true for <a href="#decl_cvNulDevReport">cvNulDevReport, cvStdErrReport</a>.
<a href="#decl_cvNulDevReport">cvGuiBoxReport</a> behaves slightly differently,
and some custom error handler may implement quite different semantics.</p>

<hr><h3><a name="decl_error_macros">ERROR Handling Macros</a></h3>
<p class="Blurb">Macros for raising an error, checking for errors etc.</p>
<pre>
/* special macros for enclosing processing statements within a function and separating
   them from prologue (resource initialization) and epilogue (guaranteed resource release) */
#define __BEGIN__       {
#define __END__         goto exit; exit: ; }
/* proceeds to "resource release" stage */
#define EXIT            goto exit

/* Declares locally the function name for CV_ERROR() use */
#define CV_FUNCNAME( Name )  \
    static char cvFuncName[] = Name

/* Raises an error within the current context */
#define CV_ERROR( Code, Msg )                                       \
{                                                                   \
     cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ );        \
     EXIT;                                                          \
}

/* Checks status after calling CXCORE function */
#define CV_CHECK()                                                  \
{                                                                   \
    if( cvGetErrStatus() &lt; 0 )                                   \
        CV_ERROR( CV_StsBackTrace, "Inner function failed." );      \
}

/* Provies shorthand for CXCORE function call and CV_CHECK() */
#define CV_CALL( Statement )                                        \
{                                                                   \
    Statement;                                                      \
    CV_CHECK();                                                     \
}

/* Checks some condition in both debug and release configurations */
#define CV_ASSERT( Condition )                                          \
{                                                                       \
    if( !(Condition) )                                                  \
        CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \
}

/* these macros are similar to their CV_... counterparts, but they
   do not need exit label nor cvFuncName to be defined */
#define OPENCV_ERROR(status,func_name,err_msg) ...
#define OPENCV_ERRCHK(func_name,err_msg) ...
#define OPENCV_ASSERT(condition,func_name,err_msg) ...
#define OPENCV_CALL(statement) ...
</pre>
Instead of a discussion, here are the documented example
of typical CXCORE function and the example of the function use.
<h4><a name="decl_error_handling_sample">Use of Error Handling Macros</a></h4>
<pre>
#include "cxcore.h"
#include &lt;stdio.h&gt;

void cvResizeDCT( CvMat* input_array, CvMat* output_array )
{
    CvMat* temp_array = 0; // declare pointer that should be released anyway.

    CV_FUNCNAME( "cvResizeDCT" ); // declare cvFuncName

    __BEGIN__; // start processing. There may be some declarations just after this macro,
               // but they couldn't be accessed from the epilogue.

    if( !CV_IS_MAT(input_array) || !CV_IS_MAT(output_array) )
        // use CV_ERROR() to raise an error
        CV_ERROR( CV_StsBadArg, "input_array or output_array are not valid matrices" );

    // some restrictions that are going to be removed later, may be checked with CV_ASSERT()
    CV_ASSERT( input_array->rows == 1 && output_array->rows == 1 );

    // use CV_CALL for safe function call
    CV_CALL( temp_array = cvCreateMat( input_array->rows, MAX(input_array->cols,output_array->cols),
                                       input_array->type ));

    if( output_array->cols &gt; input_array->cols )
        CV_CALL( cvZero( temp_array ));

    temp_array->cols = input_array->cols;
    CV_CALL( cvDCT( input_array, temp_array, CV_DXT_FORWARD ));
    temp_array->cols = output_array->cols;
    CV_CALL( cvDCT( temp_array, output_array, CV_DXT_INVERSE ));
    CV_CALL( cvScale( output_array, output_array, 1./sqrt((double)input_array->cols*output_array->cols), 0 ));

    __END__; // finish processing. Epilogue follows after the macro.

    // release temp_array. If temp_array has not been allocated before an error occured, cvReleaseMat
    // takes care of it and does nothing in this case.
    cvReleaseMat( &temp_array );
}


int main( int argc, char** argv )
{
    CvMat* src = cvCreateMat( 1, 512, CV_32F );
#if 1 /* no errors */
    CvMat* dst = cvCreateMat( 1, 256, CV_32F );
#else
    CvMat* dst = 0; /* test error processing mechanism */
#endif
    cvSet( src, cvRealScalar(1.), 0 );
#if 0 /* change 0 to 1 to suppress error handler invocation */
    cvSetErrMode( CV_ErrModeSilent );
#endif
    cvResizeDCT( src, dst ); // if some error occurs, the message box will popup, or a message will be
                             // written to log, or some user-defined processing will be done
    if( cvGetErrStatus() &lt; 0 )
        printf("Some error occured" );
    else
        printf("Everything is OK" );
    return 0;
}
</pre>


<hr><h3><a name="decl_cvGetErrStatus">GetErrStatus</a></h3>
<p class="Blurb">Returns the current error status</p>
<pre>
int cvGetErrStatus( void );
</pre><p>
The function <code>cvGetErrStatus</code> returns the current error status -
the value set with the last <a href="#decl_cvSetErrStatus">cvSetErrStatus</a> call. Note, that
in <em>Leaf</em> mode the program terminates immediately after error occured, so to
always get control after the function call, one should call <a href="#decl_cvSetErrMode">cvSetErrMode</a>
and set <em>Parent</em> or <em>Silent</em> error mode.
</p>


<hr><h3><a name="decl_cvSetErrStatus">SetErrStatus</a></h3>
<p class="Blurb">Sets the error status</p>
<pre>
void cvSetErrStatus( int status );
</pre><p><dl>
<dt>status<dd>The error status.
</dl><p>
The function <code>cvSetErrStatus</code> sets the error status to
the specified value. Mostly, the function is used to reset the error status (set to it <code>CV_StsOk</code>)
to recover after error. In other cases it is more natural to call <a href="#decl_cvError">cvError</a> or
<a href="#decl_error_macros">CV_ERROR</a>.
</p>


<hr><h3><a name="decl_cvGetErrMode">GetErrMode</a></h3>
<p class="Blurb">Returns the current error mode</p>
<pre>
int cvGetErrMode( void );
</pre><p>
The function <code>cvGetErrMode</code> returns the current error mode -
the value set with the last <a href="#decl_cvSetErrMode">cvSetErrMode</a> call.
</p>


<hr><h3><a name="decl_cvSetErrMode">SetErrMode</a></h3>
<p class="Blurb">Sets the error mode</p>
<pre>
#define CV_ErrModeLeaf    0
#define CV_ErrModeParent  1
#define CV_ErrModeSilent  2
int cvSetErrMode( int mode );
</pre><p><dl>
<dt>mode<dd>The error mode.
</dl><p>
The function <code>cvSetErrMode</code> sets the specified error mode.
For description of different error modes see the beginning of the <a href="#cxcore_system_error">section</a>.
</p>


<hr><h3><a name="decl_cvError">Error</a></h3>
<p class="Blurb">Raises an error</p>
<pre>
int cvError( int status, const char* func_name,
             const char* err_msg, const char* file_name, int line );
</pre><p><dl>
<dt>status<dd>The error status.
<dt>func_name<dd>Name of the function where the error occured.
<dt>err_msg<dd>Additional information/diagnostics about the error.
<dt>file_name<dd>Name of the file where the error occured.
<dt>line<dd>Line number, where the error occured.
</dl><p>
The function <code>cvError</code> sets the error status
to the specified value (via <a href="#decl_cvSetErrStatus">cvSetErrStatus</a>)
and, if the error mode is not <em>Silent</em>, calls the error handler.</p>


<hr><h3><a name="decl_cvErrorStr">ErrorStr</a></h3>
<p class="Blurb">Returns textual description of error status code</p>
<pre>
const char* cvErrorStr( int status );
</pre><p><dl>
<dt>status<dd>The error status.
</dl><p>
The function <code>cvErrorStr</code> returns the textual description
for the specified error status code. In case of unknown status the function returns NULL pointer.
</p>


<hr><h3><a name="decl_cvRedirectError">RedirectError</a></h3>
<p class="Blurb">Sets a new error handler</p>
<pre>
typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name,
                    const char* err_msg, const char* file_name, int line );

CvErrorCallback cvRedirectError( CvErrorCallback error_handler,
                                 void* userdata=NULL, void** prev_userdata=NULL );
</pre><p><dl>
<dt>error_handler<dd>The new error_handler.
<dt>userdata<dd>Arbitrary pointer that is transparetly passed to the error handler.
<dt>prev_userdata<dd>Pointer to the previously assigned user data pointer.
</dl><p>
The function <code>cvRedirectError</code> sets a new error handler that
can be one of <a href="#decl_cvNulDevReport">standard handlers</a> or a custom handler that has
the certain interface. The handler takes the same parameters as <a href="#decl_cvError">cvError</a>
function. If the handler returns non-zero value, the program is terminated, otherwise, it continues.
The error handler may check the current error mode with <a href="#decl_cvGetErrMode">cvGetErrMode</a>
to make a decision.
</p>


<hr><h3><a name="decl_cvNulDevReport">cvNulDevReport</a>
<a name="decl_cvStdErrReport">cvStdErrReport</a>
<a name="decl_cvGuiBoxReport">cvGuiBoxReport</a></h3>
<p class="Blurb">Provide standard error handling</p>
<pre>
int cvNulDevReport( int status, const char* func_name,
                    const char* err_msg, const char* file_name,
                    int line, void* userdata );

int cvStdErrReport( int status, const char* func_name,
                    const char* err_msg, const char* file_name,
                    int line, void* userdata );

int cvGuiBoxReport( int status, const char* func_name,
                    const char* err_msg, const char* file_name,
                    int line, void* userdata );
</pre><p><dl>
<dt>status<dd>The error status.
<dt>func_name<dd>Name of the function where the error occured.
<dt>err_msg<dd>Additional information/diagnostics about the error.
<dt>file_name<dd>Name of the file where the error occured.
<dt>line<dd>Line number, where the error occured.
<dt>userdata<dd>Pointer to the user data. Ignored by the standard handlers.
</dl><p>
The functions <code>cvNullDevReport, cvStdErrReport</code> and <code>cvGuiBoxReport</code>
provide standard error handling. <code>cvGuiBoxReport</code> is the default
error handler on Win32 systems, <code>cvStdErrReport</code> - on other systems.
<code>cvGuiBoxReport</code> pops up message box with the error description and
suggest a few options. Below is the sample message box that may be recieved with the
<a name="decl_error_handling_sample">sample code</a> above, if one introduce an error as described
in the sample</p>
<h4>Error Message Box</h4>
<p>
<img align="center" src="pics/errmsg.png" >
</p>
If the error handler is set <code>cvStdErrReport</code>, the above message will
be printed to standard error output and program will be terminated or continued, depending on the
current error mode.</p>
<h4>Error Message printed to Standard Error Output (in <em>Leaf</em> mode)</h4>
<pre>
OpenCV ERROR: Bad argument (input_array or output_array are not valid matrices)
        in function cvResizeDCT, D:\User\VP\Projects\avl_proba\a.cpp(75)
Terminating the application...
</pre>


<hr><h2><a name="cxcore_system_sys">System and Utility Functions</a></h2>

<hr><h3><a name="decl_cvAlloc">Alloc</a></h3>
<p class="Blurb">Allocates memory buffer</p>
<pre>
void* cvAlloc( size_t size );
</pre><p><dl>
<dt>size<dd>Buffer size in bytes.
</dl><p>
The function <code>cvAlloc</code> allocates <code>size</code> bytes and
returns pointer to the allocated buffer. In case of error
the function reports an error and returns NULL pointer.
By default cvAlloc calls icvAlloc which itself calls malloc,
however it is possible to assign user-defined memory allocation/deallocation
functions using <a href="#decl_cvSetMemoryManager">cvSetMemoryManager</a> function.
</p>


<hr><h3><a name="decl_cvFree">Free</a></h3>
<p class="Blurb">Deallocates memory buffer</p>
<pre>
void cvFree( T** ptr );
</pre><p><dl>
<dt>buffer<dd>Double pointer to released buffer.
</dl><p>
The function <code>cvFree</code> deallocates memory buffer allocated by <a href="#decl_cvAlloc">cvAlloc</a>.
It clears the pointer to buffer upon exit, that is why the double pointer is
used. If *buffer is already NULL, the function does nothing
</p>


<hr><h3><a name="decl_cvGetTickCount">GetTickCount</a></h3>
<p class="Blurb">Returns number of tics</p>
<pre>
int64 cvGetTickCount( void );
</pre><p>
The function <code>cvGetTickCount</code> returns number of tics
starting from some platform-dependent event (number of CPU ticks from the startup, number of milliseconds
from 1970th year etc.). The function is useful for accurate measurement of
a function/user-code execution time. To convert the number of tics to time units, use
<a href="#decl_cvGetTickFrequency">cvGetTickFrequency</a>.</p>

<hr><h3><a name="decl_cvGetTickFrequency">GetTickFrequency</a></h3>
<p class="Blurb">Returns number of tics per microsecond</p>
<pre>
double cvGetTickFrequency( void );
</pre><p>
The function <code>cvGetTickFrequency</code> returns number of tics
per microsecond. Thus, the quotient of <a href="#decl_cvGetTickCount">cvGetTickCount</a>() and
<a href="#decl_cvGetTickFrequency">cvGetTickFrequency</a>() will give a number of microseconds
starting from the platform-dependent event.</p>


<hr><h3><a name="decl_cvRegisterModule">RegisterModule</a></h3>
<p class="Blurb">Registers another module</p>
<pre>
typedef struct CvPluginFuncInfo
{
    void** func_addr;
    void* default_func_addr;
    const char* func_names;
    int search_modules;
    int loaded_from;
}
CvPluginFuncInfo;

typedef struct CvModuleInfo
{
    struct CvModuleInfo* next;
    const char* name;
    const char* version;
    CvPluginFuncInfo* func_tab;
}
CvModuleInfo;

int cvRegisterModule( const CvModuleInfo* module_info );
</pre><p><dl>
<dt>module_info<dd>Information about the module.
</dl><p>
The function <code>cvRegisterModule</code> adds module to the list of registered
modules. After the module is registered, information about it can be retrieved
using <a href="#decl_cvGetModuleInfo">cvGetModuleInfo</a> function. Also, the registered module
makes full use of optimized plugins (IPP, MKL, ...), supported by CXCORE.
CXCORE itself, CV (computer vision), CVAUX (auxilary computer vision) and HIGHGUI
(visualization & image/video acquisition) are examples of modules. Registration is usually done
then the shared library is loaded. See cxcore/src/cxswitcher.cpp and cv/src/cvswitcher.cpp
for details, how registration is done and
look at cxcore/src/cxswitcher.cpp, cxcore/src/_cxipp.h on how IPP and MKL are connected to the modules.</p>


<hr><h3><a name="decl_cvGetModuleInfo">GetModuleInfo</a></h3>
<p class="Blurb">Retrieves information about the registered module(s) and plugins</p>
<pre>
void  cvGetModuleInfo( const char* module_name,
                       const char** version,
                       const char** loaded_addon_plugins );
</pre><p><dl>
<dt>module_name<dd>Name of the module of interest, or NULL, which means all the modules.
<dt>version<dd>The output parameter. Information about the module(s), including version.
<dt>loaded_addon_plugins<dd>The list of names and versions of the optimized plugins that CXCORE was
        able to find and load.
</dl><p>
The function <code>cvGetModuleInfo</code> returns information about one of
or all of the registered modules. The returned information is stored inside the libraries, so
user should not deallocate or modify the returned text strings.</p>


<hr><h3><a name="decl_cvUseOptimized">UseOptimized</a></h3>
<p class="Blurb">Switches between optimized/non-optimized modes</p>
<pre>
int cvUseOptimized( int on_off );
</pre><p><dl>
<dt>on_off<dd>Use optimized (&lt;&gt;0) or not (0).
</dl><p>
The function <code>cvUseOptimized</code> switches between the mode, where
only pure C implementations from cxcore, OpenCV etc. are used, and the mode, where
IPP and MKL functions are used if available. When <code>cvUseOptimized(0)</code> is called,
all the optimized libraries are unloaded. The function may be useful for debugging, IPP&MKL upgrade
on the fly, online speed comparisons etc. It returns the number of optimized functions loaded.
Note that by default the optimized plugins are loaded, so it is not necessary to
call <code>cvUseOptimized(1)</code> in the beginning of the program (actually, it will only
increase the startup time)</p>


<hr><h3><a name="decl_cvSetMemoryManager">SetMemoryManager</a></h3>
<p class="Blurb">Assings custom/default memory managing functions</p>
<pre>
typedef void* (CV_CDECL *CvAllocFunc)(size_t size, void* userdata);
typedef int (CV_CDECL *CvFreeFunc)(void* pptr, void* userdata);

void cvSetMemoryManager( CvAllocFunc alloc_func=NULL,
                         CvFreeFunc free_func=NULL,
                         void* userdata=NULL );
</pre><p><dl>
<dt>alloc_func<dd>Allocation function; the interface is similar to <code>malloc</code>, except that <code>userdata</code>
              may be used to determine the context.
<dt>free_func<dd>Deallocation function; the interface is similar to <code>free</code>.
<dt>userdata<dd>User data that is transparetly passed to the custom functions.
</dl><p>
The function <code>cvSetMemoryManager</code>
sets user-defined memory managment functions (substitutors for malloc and free) that
will be called by cvAlloc, cvFree and higher-level functions (e.g. cvCreateImage).
Note, that the function should be called when there is data allocated using <a href="#decl_cvAlloc">cvAlloc<a>.
Also, to avoid infinite recursive calls, it is not allowed to call <a href="#decl_cvAlloc">cvAlloc</a>
and <a href="#decl_cvFree">cvFree</a> from the custom allocation/deallocation functions.</p>
<p>
If <code>alloc_func</code> and <code>free_func</code> pointers are <code>NULL</code>,
the default memory managing functions are restored.</p>


<hr><h3><a name="decl_cvSetIPLAllocators">SetIPLAllocators</a></h3>
<p class="Blurb">Switches to IPL functions for image allocation/deallocation</p>
<pre>
typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader)
                            (int,int,int,char*,char*,int,int,int,int,int,
                            IplROI*,IplImage*,void*,IplTileInfo*);
typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int);
typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int);
typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int);
typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*);

void cvSetIPLAllocators( Cv_iplCreateImageHeader create_header,
                         Cv_iplAllocateImageData allocate_data,
                         Cv_iplDeallocate deallocate,
                         Cv_iplCreateROI create_roi,
                         Cv_iplCloneImage clone_image );

#define CV_TURN_ON_IPL_COMPATIBILITY()                                  \
    cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage,         \
                        iplDeallocate, iplCreateROI, iplCloneImage )
</pre><p><dl>
<dt>create_header<dd>Pointer to iplCreateImageHeader.
<dt>allocate_data<dd>Pointer to iplAllocateImage.
<dt>deallocate<dd>Pointer to iplDeallocate.
<dt>create_roi<dd>Pointer to iplCreateROI.
<dt>clone_image<dd>Pointer to iplCloneImage.
</dl><p>
The function <code>cvSetIPLAllocators</code>
makes CXCORE to use IPL functions for image allocation/deallocation operations.
For convenience, there is the wrapping macro <code>CV_TURN_ON_IPL_COMPATIBILITY</code>.
The function is useful for applications where IPL and CXCORE/OpenCV are used together and still
there are calls to <code>iplCreateImageHeader</code> etc. The function is not necessary if
IPL is called only for data processing and all the allocation/deallocation is done by CXCORE,
or if all the allocation/deallocation is done by IPL and some of OpenCV functions are used to
process the data.</p>


<hr><h3><a name="decl_cvGetNumThreads">GetNumThreads</a></h3>
<p class="Blurb">Returns the current number of threads used</p>
<pre>
int cvGetNumThreads(void);
</pre>
<p>
The function <code>cvGetNumThreads</code> return the current number of threads
that are used by parallelized (via OpenMP) OpenCV functions.</p>


<hr><h3><a name="decl_cvSetNumThreads">SetNumThreads</a></h3>
<p class="Blurb">Sets the number of threads</p>
<pre>
void cvSetNumThreads( int threads=0 );
</pre><p><dl>
<dt>threads<dd>The number of threads.
</dl><p>
The function <code>cvSetNumThreads</code> sets the number of threads
that are used by parallelized OpenCV functions. When the argument
is zero or negative, and at the beginning of the program,
the number of threads is set to the number of processors in the system,
as returned by the function <code>omp_get_num_procs()</code> from OpenMP runtime.
</p>


<hr><h3><a name="decl_cvGetThreadNum">GetThreadNum</a></h3>
<p class="Blurb">Returns index of the current thread</p>
<pre>
int cvGetThreadNum( void );
</pre><p>
The function <code>cvGetThreadNum</code> returns the index, from 0 to
<a href="#decl_cvGetNumThreads">cvGetNumThreads</a>()-1, of the thread that called the function.
It is a wrapper for the function <code>omp_get_thread_num()</code> from OpenMP runtime.
The retrieved index may be used to access local-thread data inside the parallelized code fragments.
</p>


<hr><h1><a name="cxcore_func_index">Alphabetical List of Functions</a></h1>

<hr><h3>A</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvAbsDiff">AbsDiff</a></td>
<td width="25%"><a href="#decl_cvAddWeighted">AddWeighted</a></td>
<td width="25%"><a href="#decl_cvAvg">Avg</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvAbsDiffS">AbsDiffS</a></td>
<td width="25%"><a href="#decl_cvAlloc">Alloc</a></td>
<td width="25%"><a href="#decl_cvAvgSdv">AvgSdv</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvAdd">Add</a></td>
<td width="25%"><a href="#decl_cvAnd">And</a></td>
<td width="25%%"></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvAddS">AddS</a></td>
<td width="25%"><a href="#decl_cvAndS">AndS</a></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>B</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvBackProjectPCA">BackProjectPCA</a></td>
<td width="25%%"></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>C</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvCalcCovarMatrix">CalcCovarMatrix</a></td>
<td width="25%"><a href="#decl_cvCloneGraph">CloneGraph</a></td>
<td width="25%"><a href="#decl_cvCreateGraph">CreateGraph</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvCalcPCA">CalcPCA</a></td>
<td width="25%"><a href="#decl_cvCloneImage">CloneImage</a></td>
<td width="25%"><a href="#decl_cvCreateGraphScanner">CreateGraphScanner</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvCartToPolar">CartToPolar</a></td>
<td width="25%"><a href="#decl_cvCloneMat">CloneMat</a></td>
<td width="25%"><a href="#decl_cvCreateImage">CreateImage</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvCbrt">Cbrt</a></td>
<td width="25%"><a href="#decl_cvCloneMatND">CloneMatND</a></td>
<td width="25%"><a href="#decl_cvCreateImageHeader">CreateImageHeader</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvCheckArr">CheckArr</a></td>
<td width="25%"><a href="#decl_cvCloneSeq">CloneSeq</a></td>
<td width="25%"><a href="#decl_cvCreateMat">CreateMat</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvCircle">Circle</a></td>
<td width="25%"><a href="#decl_cvCloneSparseMat">CloneSparseMat</a></td>
<td width="25%"><a href="#decl_cvCreateMatHeader">CreateMatHeader</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvClearGraph">ClearGraph</a></td>
<td width="25%"><a href="#decl_cvCmp">Cmp</a></td>
<td width="25%"><a href="#decl_cvCreateMatND">CreateMatND</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvClearMemStorage">ClearMemStorage</a></td>
<td width="25%"><a href="#decl_cvCmpS">CmpS</a></td>
<td width="25%"><a href="#decl_cvCreateMatNDHeader">CreateMatNDHeader</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvClearND">ClearND</a></td>
<td width="25%"><a href="#decl_cvConvertScale">ConvertScale</a></td>
<td width="25%"><a href="#decl_cvCreateMemStorage">CreateMemStorage</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvClearSeq">ClearSeq</a></td>
<td width="25%"><a href="#decl_cvConvertScaleAbs">ConvertScaleAbs</a></td>
<td width="25%"><a href="#decl_cvCreateSeq">CreateSeq</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvClearSet">ClearSet</a></td>
<td width="25%"><a href="#decl_cvCopy">Copy</a></td>
<td width="25%"><a href="#decl_cvCreateSet">CreateSet</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvClipLine">ClipLine</a></td>
<td width="25%"><a href="#decl_cvCountNonZero">CountNonZero</a></td>
<td width="25%"><a href="#decl_cvCreateSparseMat">CreateSparseMat</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvClipLine">ClipLine</a></td>
<td width="25%"><a href="#decl_cvCreateChildMemStorage">CreateChildMemStorage</a></td>
<td width="25%"><a href="#decl_cvCrossProduct">CrossProduct</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvClone">Clone</a></td>
<td width="25%"><a href="#decl_cvCreateData">CreateData</a></td>
<td width="25%"><a href="#decl_cvCvtSeqToArray">CvtSeqToArray</a></td>
</tr>
</table>
<hr><h3>D</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvDCT">DCT</a></td>
<td width="25%"><a href="#decl_cvDet">Det</a></td>
<td width="25%"><a href="#decl_cvDrawContours">DrawContours</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvDFT">DFT</a></td>
<td width="25%"><a href="#decl_cvDiv">Div</a></td>
<td width="25%%"></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvDecRefData">DecRefData</a></td>
<td width="25%"><a href="#decl_cvDotProduct">DotProduct</a></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>E</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvEigenVV">EigenVV</a></td>
<td width="25%"><a href="#decl_cvEllipseBox">EllipseBox</a></td>
<td width="25%"><a href="#decl_cvError">Error</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvEllipse">Ellipse</a></td>
<td width="25%"><a href="#decl_cvEndWriteSeq">EndWriteSeq</a></td>
<td width="25%"><a href="#decl_cvErrorStr">ErrorStr</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvEllipse2Poly">Ellipse2Poly</a></td>
<td width="25%"><a href="#decl_cvEndWriteStruct">EndWriteStruct</a></td>
<td width="25%"><a href="#decl_cvExp">Exp</a></td>
</tr>
</table>
<hr><h3>F</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvFastArctan">FastArctan</a></td>
<td width="25%"><a href="#decl_cvFindGraphEdgeByPtr">FindGraphEdgeByPtr</a></td>
<td width="25%"><a href="#decl_cvFlushSeqWriter">FlushSeqWriter</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvFillConvexPoly">FillConvexPoly</a></td>
<td width="25%"><a href="#decl_cvFindType">FindType</a></td>
<td width="25%"><a href="#decl_cvFree">Free</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvFillPoly">FillPoly</a></td>
<td width="25%"><a href="#decl_cvFirstType">FirstType</a></td>
<td width="25%%"></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvFindGraphEdge">FindGraphEdge</a></td>
<td width="25%"><a href="#decl_cvFlip">Flip</a></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>G</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvGEMM">GEMM</a></td>
<td width="25%"><a href="#decl_cvGetMat">GetMat</a></td>
<td width="25%"><a href="#decl_cvGetTickCount">GetTickCount</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGet*D">Get*D</a></td>
<td width="25%"><a href="#decl_cvGetModuleInfo">GetModuleInfo</a></td>
<td width="25%"><a href="#decl_cvGetTickFrequency">GetTickFrequency</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetCol">GetCol</a></td>
<td width="25%"><a href="#decl_cvGetNextSparseNode">GetNextSparseNode</a></td>
<td width="25%"><a href="#decl_cvGraphAddEdge">GraphAddEdge</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetDiag">GetDiag</a></td>
<td width="25%"><a href="#decl_cvGetNumThreads">GetNumThreads</a></td>
<td width="25%"><a href="#decl_cvGraphAddEdgeByPtr">GraphAddEdgeByPtr</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetDims">GetDims</a></td>
<td width="25%"><a href="#decl_cvGetOptimalDFTSize">GetOptimalDFTSize</a></td>
<td width="25%"><a href="#decl_cvGraphAddVtx">GraphAddVtx</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetElemType">GetElemType</a></td>
<td width="25%"><a href="#decl_cvGetRawData">GetRawData</a></td>
<td width="25%"><a href="#decl_cvGraphEdgeIdx">GraphEdgeIdx</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetErrMode">GetErrMode</a></td>
<td width="25%"><a href="#decl_cvGetReal*D">GetReal*D</a></td>
<td width="25%"><a href="#decl_cvGraphRemoveEdge">GraphRemoveEdge</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetErrStatus">GetErrStatus</a></td>
<td width="25%"><a href="#decl_cvGetRootFileNode">GetRootFileNode</a></td>
<td width="25%"><a href="#decl_cvGraphRemoveEdgeByPtr">GraphRemoveEdgeByPtr</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetFileNode">GetFileNode</a></td>
<td width="25%"><a href="#decl_cvGetRow">GetRow</a></td>
<td width="25%"><a href="#decl_cvGraphRemoveVtx">GraphRemoveVtx</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetFileNodeByName">GetFileNodeByName</a></td>
<td width="25%"><a href="#decl_cvGetSeqElem">GetSeqElem</a></td>
<td width="25%"><a href="#decl_cvGraphRemoveVtxByPtr">GraphRemoveVtxByPtr</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetFileNodeName">GetFileNodeName</a></td>
<td width="25%"><a href="#decl_cvGetSeqReaderPos">GetSeqReaderPos</a></td>
<td width="25%"><a href="#decl_cvGraphVtxDegree">GraphVtxDegree</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetGraphVtx">GetGraphVtx</a></td>
<td width="25%"><a href="#decl_cvGetSetElem">GetSetElem</a></td>
<td width="25%"><a href="#decl_cvGraphVtxDegreeByPtr">GraphVtxDegreeByPtr</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetHashedKey">GetHashedKey</a></td>
<td width="25%"><a href="#decl_cvGetSize">GetSize</a></td>
<td width="25%"><a href="#decl_cvGraphVtxIdx">GraphVtxIdx</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetImage">GetImage</a></td>
<td width="25%"><a href="#decl_cvGetSubRect">GetSubRect</a></td>
<td width="25%"><a href="#decl_cvGuiBoxReport">GuiBoxReport</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetImageCOI">GetImageCOI</a></td>
<td width="25%"><a href="#decl_cvGetTextSize">GetTextSize</a></td>
<td width="25%"><a href="#decl_cvmGet">Get</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvGetImageROI">GetImageROI</a></td>
<td width="25%"><a href="#decl_cvGetThreadNum">GetThreadNum</a></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>I</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvInRange">InRange</a></td>
<td width="25%"><a href="#decl_cvInitLineIterator">InitLineIterator</a></td>
<td width="25%"><a href="#decl_cvInsertNodeIntoTree">InsertNodeIntoTree</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvInRangeS">InRangeS</a></td>
<td width="25%"><a href="#decl_cvInitMatHeader">InitMatHeader</a></td>
<td width="25%"><a href="#decl_cvInvSqrt">InvSqrt</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvIncRefData">IncRefData</a></td>
<td width="25%"><a href="#decl_cvInitMatNDHeader">InitMatNDHeader</a></td>
<td width="25%"><a href="#decl_cvInvert">Invert</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvInitFont">InitFont</a></td>
<td width="25%"><a href="#decl_cvInitSparseMatIterator">InitSparseMatIterator</a></td>
<td width="25%"><a href="#decl_cvIsInf">IsInf</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvInitImageHeader">InitImageHeader</a></td>
<td width="25%"><a href="#decl_cvInitTreeNodeIterator">InitTreeNodeIterator</a></td>
<td width="25%"><a href="#decl_cvIsNaN">IsNaN</a></td>
</tr>
</table>
<hr><h3>K</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvKMeans2">KMeans2</a></td>
<td width="25%%"></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>L</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvLUT">LUT</a></td>
<td width="25%"><a href="#decl_cvLoad">Load</a></td>
<td width="25%%"></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvLine">Line</a></td>
<td width="25%"><a href="#decl_cvLog">Log</a></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>M</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvMahalonobis">Mahalonobis</a></td>
<td width="25%"><a href="#decl_cvMemStorageAlloc">MemStorageAlloc</a></td>
<td width="25%"><a href="#decl_cvMinS">MinS</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvMakeSeqHeaderForArray">MakeSeqHeaderForArray</a></td>
<td width="25%"><a href="#decl_cvMemStorageAllocString">MemStorageAllocString</a></td>
<td width="25%"><a href="#decl_cvMixChannels">MixChannels</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvMat">Mat</a></td>
<td width="25%"><a href="#decl_cvMerge">Merge</a></td>
<td width="25%"><a href="#decl_cvMul">Mul</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvMax">Max</a></td>
<td width="25%"><a href="#decl_cvMin">Min</a></td>
<td width="25%"><a href="#decl_cvMulSpectrums">MulSpectrums</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvMaxS">MaxS</a></td>
<td width="25%"><a href="#decl_cvMinMaxLoc">MinMaxLoc</a></td>
<td width="25%"><a href="#decl_cvMulTransposed">MulTransposed</a></td>
</tr>
</table>
<hr><h3>N</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvNextGraphItem">NextGraphItem</a></td>
<td width="25%"><a href="#decl_cvNorm">Norm</a></td>
<td width="25%"><a href="#decl_cvNot">Not</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvNextTreeNode">NextTreeNode</a></td>
<td width="25%"><a href="#decl_cvNormalize">Normalize</a></td>
<td width="25%"><a href="#decl_cvNulDevReport">NulDevReport</a></td>
</tr>
</table>
<hr><h3>O</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvOpenFileStorage">OpenFileStorage</a></td>
<td width="25%"><a href="#decl_cvOr">Or</a></td>
<td width="25%"><a href="#decl_cvOrS">OrS</a></td>
</tr>
</table>
<hr><h3>P</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvPerspectiveTransform">PerspectiveTransform</a></td>
<td width="25%"><a href="#decl_cvPow">Pow</a></td>
<td width="25%"><a href="#decl_cvPtr*D">Ptr*D</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvPolarToCart">PolarToCart</a></td>
<td width="25%"><a href="#decl_cvPrevTreeNode">PrevTreeNode</a></td>
<td width="25%"><a href="#decl_cvPutText">PutText</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvPolyLine">PolyLine</a></td>
<td width="25%"><a href="#decl_cvProjectPCA">ProjectPCA</a></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>R</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvRNG">RNG</a></td>
<td width="25%"><a href="#decl_cvReadRealByName">ReadRealByName</a></td>
<td width="25%"><a href="#decl_cvReleaseImageHeader">ReleaseImageHeader</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvRandArr">RandArr</a></td>
<td width="25%"><a href="#decl_cvReadString">ReadString</a></td>
<td width="25%"><a href="#decl_cvReleaseMat">ReleaseMat</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvRandInt">RandInt</a></td>
<td width="25%"><a href="#decl_cvReadStringByName">ReadStringByName</a></td>
<td width="25%"><a href="#decl_cvReleaseMatND">ReleaseMatND</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvRandReal">RandReal</a></td>
<td width="25%"><a href="#decl_cvRectangle">Rectangle</a></td>
<td width="25%"><a href="#decl_cvReleaseMemStorage">ReleaseMemStorage</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvRandShuffle">RandShuffle</a></td>
<td width="25%"><a href="#decl_cvRedirectError">RedirectError</a></td>
<td width="25%"><a href="#decl_cvReleaseSparseMat">ReleaseSparseMat</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvRange">Range</a></td>
<td width="25%"><a href="#decl_cvReduce">Reduce</a></td>
<td width="25%"><a href="#decl_cvRemoveNodeFromTree">RemoveNodeFromTree</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvRead">Read</a></td>
<td width="25%"><a href="#decl_cvRegisterModule">RegisterModule</a></td>
<td width="25%"><a href="#decl_cvRepeat">Repeat</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvReadByName">ReadByName</a></td>
<td width="25%"><a href="#decl_cvRegisterType">RegisterType</a></td>
<td width="25%"><a href="#decl_cvResetImageROI">ResetImageROI</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvReadInt">ReadInt</a></td>
<td width="25%"><a href="#decl_cvRelease">Release</a></td>
<td width="25%"><a href="#decl_cvReshape">Reshape</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvReadIntByName">ReadIntByName</a></td>
<td width="25%"><a href="#decl_cvReleaseData">ReleaseData</a></td>
<td width="25%"><a href="#decl_cvReshapeMatND">ReshapeMatND</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvReadRawData">ReadRawData</a></td>
<td width="25%"><a href="#decl_cvReleaseFileStorage">ReleaseFileStorage</a></td>
<td width="25%"><a href="#decl_cvRestoreMemStoragePos">RestoreMemStoragePos</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvReadRawDataSlice">ReadRawDataSlice</a></td>
<td width="25%"><a href="#decl_cvReleaseGraphScanner">ReleaseGraphScanner</a></td>
<td width="25%"><a href="#decl_cvRound">Round</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvReadReal">ReadReal</a></td>
<td width="25%"><a href="#decl_cvReleaseImage">ReleaseImage</a></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>S</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvSVBkSb">SVBkSb</a></td>
<td width="25%"><a href="#decl_cvSeqSlice">SeqSlice</a></td>
<td width="25%"><a href="#decl_cvSetSeqReaderPos">SetSeqReaderPos</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSVD">SVD</a></td>
<td width="25%"><a href="#decl_cvSeqSort">SeqSort</a></td>
<td width="25%"><a href="#decl_cvSetZero">SetZero</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSave">Save</a></td>
<td width="25%"><a href="#decl_cvSet">Set</a></td>
<td width="25%"><a href="#decl_cvSolve">Solve</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSaveMemStoragePos">SaveMemStoragePos</a></td>
<td width="25%"><a href="#decl_cvSet*D">Set*D</a></td>
<td width="25%"><a href="#decl_cvSolveCubic">SolveCubic</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvScaleAdd">ScaleAdd</a></td>
<td width="25%"><a href="#decl_cvSetAdd">SetAdd</a></td>
<td width="25%"><a href="#decl_cvSplit">Split</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqElemIdx">SeqElemIdx</a></td>
<td width="25%"><a href="#decl_cvSetData">SetData</a></td>
<td width="25%"><a href="#decl_cvSqrt">Sqrt</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqInsert">SeqInsert</a></td>
<td width="25%"><a href="#decl_cvSetErrMode">SetErrMode</a></td>
<td width="25%"><a href="#decl_cvStartAppendToSeq">StartAppendToSeq</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqInsertSlice">SeqInsertSlice</a></td>
<td width="25%"><a href="#decl_cvSetErrStatus">SetErrStatus</a></td>
<td width="25%"><a href="#decl_cvStartNextStream">StartNextStream</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqInvert">SeqInvert</a></td>
<td width="25%"><a href="#decl_cvSetIPLAllocators">SetIPLAllocators</a></td>
<td width="25%"><a href="#decl_cvStartReadRawData">StartReadRawData</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqPartition">SeqPartition</a></td>
<td width="25%"><a href="#decl_cvSetIdentity">SetIdentity</a></td>
<td width="25%"><a href="#decl_cvStartReadSeq">StartReadSeq</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqPop">SeqPop</a></td>
<td width="25%"><a href="#decl_cvSetImageCOI">SetImageCOI</a></td>
<td width="25%"><a href="#decl_cvStartWriteSeq">StartWriteSeq</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqPopFront">SeqPopFront</a></td>
<td width="25%"><a href="#decl_cvSetImageROI">SetImageROI</a></td>
<td width="25%"><a href="#decl_cvStartWriteStruct">StartWriteStruct</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqPopMulti">SeqPopMulti</a></td>
<td width="25%"><a href="#decl_cvSetMemoryManager">SetMemoryManager</a></td>
<td width="25%"><a href="#decl_cvStdErrReport">StdErrReport</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqPush">SeqPush</a></td>
<td width="25%"><a href="#decl_cvSetNew">SetNew</a></td>
<td width="25%"><a href="#decl_cvSub">Sub</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqPushFront">SeqPushFront</a></td>
<td width="25%"><a href="#decl_cvSetNumThreads">SetNumThreads</a></td>
<td width="25%"><a href="#decl_cvSubRS">SubRS</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqPushMulti">SeqPushMulti</a></td>
<td width="25%"><a href="#decl_cvSetReal*D">SetReal*D</a></td>
<td width="25%"><a href="#decl_cvSubS">SubS</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqRemove">SeqRemove</a></td>
<td width="25%"><a href="#decl_cvSetRemove">SetRemove</a></td>
<td width="25%"><a href="#decl_cvSum">Sum</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqRemoveSlice">SeqRemoveSlice</a></td>
<td width="25%"><a href="#decl_cvSetRemoveByPtr">SetRemoveByPtr</a></td>
<td width="25%"><a href="#decl_cvmSet">Set</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvSeqSearch">SeqSearch</a></td>
<td width="25%"><a href="#decl_cvSetSeqBlockSize">SetSeqBlockSize</a></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>T</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvTrace">Trace</a></td>
<td width="25%"><a href="#decl_cvTranspose">Transpose</a></td>
<td width="25%"><a href="#decl_cvTypeOf">TypeOf</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvTransform">Transform</a></td>
<td width="25%"><a href="#decl_cvTreeToNodeSeq">TreeToNodeSeq</a></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>U</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvUnregisterType">UnregisterType</a></td>
<td width="25%"><a href="#decl_cvUseOptimized">UseOptimized</a></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>W</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvWrite">Write</a></td>
<td width="25%"><a href="#decl_cvWriteInt">WriteInt</a></td>
<td width="25%"><a href="#decl_cvWriteString">WriteString</a></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvWriteComment">WriteComment</a></td>
<td width="25%"><a href="#decl_cvWriteRawData">WriteRawData</a></td>
<td width="25%%"></td>
</tr>
<tr>
<td width="25%"><a href="#decl_cvWriteFileNode">WriteFileNode</a></td>
<td width="25%"><a href="#decl_cvWriteReal">WriteReal</a></td>
<td width="25%%"></td>
</tr>
</table>
<hr><h3>X</h3>
<table width="100%">
<tr>
<td width="25%"><a href="#decl_cvXor">Xor</a></td>
<td width="25%"><a href="#decl_cvXorS">XorS</a></td>
<td width="25%%"></td>
</tr>
</table>

<hr><h1><a name="cxcore_sample_index">List of Examples</a></h1>

</body>
</html>
